Skip to content

Commit 68dbd87

Browse files
committed
Move hoisted closures inside the render closure body
Avoids polluting the scope of the caller when a precompiled template is loaded via include/require, and removes the need for a use() clause on the top-level render closure. Partial templates also no longer need an IIFE to scope their sub-program definitions.
1 parent 1bc1289 commit 68dbd87

1 file changed

Lines changed: 6 additions & 16 deletions

File tree

src/Compiler.php

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,6 @@ final class Compiler
6161
* @var string[][]
6262
*/
6363
private array $programDepStack = [];
64-
/**
65-
* Deps for the top-level render closure — set by compile() after compileProgram() returns.
66-
* @var string[]
67-
*/
68-
private array $renderDeps = [];
6964

7065
public function __construct(
7166
private readonly Parser $parser,
@@ -79,7 +74,7 @@ public function compile(Program $program, Context $context): string
7974
$this->programDefs = [];
8075
$this->programDepStack = [[]];
8176
$code = $this->compileProgram($program);
82-
$this->renderDeps = array_pop($this->programDepStack);
77+
array_pop($this->programDepStack);
8378
return $code;
8479
}
8580

@@ -91,10 +86,9 @@ public function compile(Program $program, Context $context): string
9186
public function composePHPRender(string $code): string
9287
{
9388
$partials = implode(",\n", $this->context->partialCode);
94-
$useVars = implode(', ', $this->renderDeps);
95-
$closure = self::templateClosure($code, $partials, "\n \$in = &\$cx->data['root'];", $useVars);
96-
$defs = $this->programDefs ? implode("\n", $this->programDefs) . "\n" : '';
97-
return "use " . Runtime::class . " as LR;\n{$defs}return $closure;";
89+
$defs = $this->programDefs ? "\n " . implode("\n ", $this->programDefs) : '';
90+
$closure = self::templateClosure($code, $partials, $defs . "\n \$in = &\$cx->data['root'];");
91+
return "use " . Runtime::class . " as LR;\nreturn $closure;";
9892
}
9993

10094
/**
@@ -699,12 +693,8 @@ private function compilePartialTemplate(string $name, string $template): void
699693
$program = $this->parser->parse($template, $this->context->options->ignoreStandalone);
700694
$partialCompiler = new self($this->parser);
701695
$code = $partialCompiler->compile($program, $this->context);
702-
$closureExpr = self::templateClosure($code, useVars: implode(', ', $partialCompiler->renderDeps));
703-
704-
if ($partialCompiler->programDefs) {
705-
$defs = implode("\n", $partialCompiler->programDefs) . "\n";
706-
$closureExpr = "(static function() {\n{$defs}return {$closureExpr};\n})()";
707-
}
696+
$defs = $partialCompiler->programDefs ? "\n " . implode("\n ", $partialCompiler->programDefs) : '';
697+
$closureExpr = self::templateClosure($code, stmts: $defs);
708698

709699
$this->context->partialCode[$name] = self::quote($name) . ' => ' . $closureExpr;
710700
}

0 commit comments

Comments
 (0)