forked from ircmaxell/php-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRuntime.php
More file actions
executable file
·780 lines (693 loc) · 27 KB
/
Runtime.php
File metadata and controls
executable file
·780 lines (693 loc) · 27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
<?php
/*
* This file is part of PHP-Compiler, a PHP CFG Compiler for PHP code
*
* @copyright 2015 Anthony Ferrara. All rights reserved
* @license MIT See LICENSE at the root of the project for more info
*/
namespace PHPCompiler;
use PHPCfg\Func as CfgFunc;
use PHPCfg\Parser;
use PHPCfg\Traverser;
use PHPCfg\LivenessDetector as CfgLivenessDetector;
use PHPCfg\Visitor;
use PHPCfg\Script;
use PHPTypes\TypeReconstructor;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor;
use PhpParser\ParserFactory;
use PHPTypes\State;
use PHPCompiler\VM\Optimizer;
use PHPCompiler\VM\Context as VMContext;
use PHPCompiler\VM\ObjectRegistry;
use PHPCompiler\JIT\Context as JITContext;
use PHPCompiler\Ast\AsymmetricVisibilityRewriter;
use PHPCompiler\Ast\GroupUseStripper;
use PHPCompiler\Ast\SealedClassAnnotator;
use PHPCompiler\Ast\SealedClassPreprocessor;
use PHPCompiler\Ast\InOperatorDesugar;
use PHPCompiler\Ast\PipeOperatorDesugar;
use PHPCompiler\Visitor\InOperatorResolver;
use PHPCompiler\Web\Superglobals;
use PHPCompiler\Lint\LintCompiler;
use PHPCompiler\VM\OutputBuffer;
use PHPCompiler\VM\ShutdownQueue;
class Runtime {
const MODE_NORMAL = 0b0001;
const MODE_AOT = 0b0010;
public Compiler $compiler;
public Parser $parser;
public Traverser $preprocessor;
public Traverser $postprocessor;
private Ast\AbstractEnumMarker $abstractEnumMarker;
public CfgLivenessDetector $detector;
public Optimizer $assignOpResolver;
public VMContext $vmContext;
public ?VM $vm = null;
private ?JITContext $jitContext = null;
private ?JIT $jit = null;
private bool $jitLoadedFromDiskCache = false;
private ?string $jitCompileCacheKey = null;
public array $modules = [];
public int $mode;
private SealedClassAnnotator $sealedClassAnnotator;
public ?string $debugFile = null;
public TypeReconstructor $typeReconstructor;
/** Last parse/compile failure for native M3 emit bridge (#3037). */
private static ?string $lastParseFailure = null;
/**
* Whether parse/compile null diagnostics should be emitted (#2988).
*/
public static function isParseDiagEnabled(): bool
{
if (JIT\EmitTuMode::isMinimalRuntime()) {
return true;
}
if (!\function_exists('getenv')) {
return false;
}
foreach (['PHP_COMPILER_PARSE_DIAG', 'PHP_COMPILER_SELFHOST_AOT', 'PHP_COMPILER_M3_COMPILE_MODE'] as $name) {
$value = getenv($name);
if (false !== $value && ('1' === $value || 'true' === strtolower((string) $value))) {
return true;
}
}
return false;
}
public function __construct(int $mode = self::MODE_NORMAL) {
ObjectRegistry::reset();
self::clearLastParseFailure();
$this->mode = $mode;
$this->initParsePipeline();
$this->initCompiler();
$this->initVmContext();
$this->loadCoreModules();
}
/** PhpParser + PHPCfg traversers; LLVM 9 crashes when inlined in __construct (#1402, #1494). */
private function initParsePipeline(): void {
$astTraverser = new NodeTraverser;
$astTraverser->addVisitor(
new NodeVisitor\NameResolver
);
$astTraverser->addVisitor(new GroupUseStripper());
$this->abstractEnumMarker = new Ast\AbstractEnumMarker();
$astTraverser->addVisitor($this->abstractEnumMarker);
$this->sealedClassAnnotator = new SealedClassAnnotator();
$astTraverser->addVisitor($this->sealedClassAnnotator);
$this->parser = new Parser(
(new ParserFactory)->create(ParserFactory::ONLY_PHP7),
$astTraverser
);
$this->preprocessor = new Traverser;
$this->preprocessor->addVisitor(new InOperatorResolver);
$this->preprocessor->addVisitor(new Visitor\Simplifier);
$this->preprocessor->addVisitor(new Visitor\DeadBlockEliminator);
$this->postprocessor = new Traverser;
$this->postprocessor->addVisitor(new Visitor\PhiResolver);
$this->detector = new NullSafeLivenessDetector;
$this->assignOpResolver = new Optimizer\AssignOp;
$this->typeReconstructor = new TypeReconstructor;
}
/**
* M5 vendor prelink compiles curated vendor bundles for cold boot. Some vendor doc-comments can
* contain junk type fragments that upstream PHPTypes rejects (issue #2751 / #2743).
*
* This is intentionally bootstrap-only: keep normal compilation strict.
*/
private function isBootstrapVendorPrelinkMode(): bool
{
$flag = getenv('PHP_COMPILER_VENDOR_PRELINK');
return '1' === $flag || 'true' === strtolower((string) $flag);
}
/** Compiler instance; split from VMContext for M3 link (#1494). */
private function initCompiler(): void {
$this->compiler = new Compiler;
}
/** VMContext only; `new VM` deferred to run() (#1494). */
private function initVmContext(): void {
$this->vmContext = new VMContext($this);
}
private function ensureVm(): void {
if (null === $this->vm) {
$this->vm = new VM($this->vmContext);
}
}
public function vm(): VM {
$this->ensureVm();
return $this->vm;
}
public function __destruct() {
foreach ($this->modules as $module) {
$module->shutdown();
}
}
public function setDebug(?string $debugFile = null): void {
$this->debugFile = $debugFile;
}
public function setAotDebugSymbols(bool $enabled = true): void
{
if ($enabled) {
JIT\AotDebugSymbols::enable();
}
}
private function loadCoreModules(): void {
$this->load(new ext\types\Module);
$this->load(new ext\spl\Module);
$this->load(new ext\intl\Module);
$this->load(new ext\zip\Module);
$this->load(new ext\mbstring\Module);
$this->load(new ext\filter\Module);
$this->load(new ext\bcmath\Module);
$this->load(new ext\standard\Module);
}
public function loadJit(): JIT {
if (is_null($this->jit)) {
$this->jit = $this->createJit($this->jitContextForLoadJit());
if (!$this->shouldSkipLoadJitCompileModuleFuncs()) {
$this->loadJitCompileModuleFuncs($this->jit);
}
}
return $this->jit;
}
/** M3 emit smoke: compile main block only; skip eager ext/ JIT (#1983, #2599). */
private function shouldSkipLoadJitCompileModuleFuncs(): bool
{
if (JIT\CompileCache::shouldSkipModuleFuncCompile()) {
return true;
}
if (JIT\EmitTuMode::isMinimalRuntime()) {
return true;
}
$loadType = $this->mode === self::MODE_NORMAL
? JIT\Builtin::LOAD_TYPE_EMBED
: JIT\Builtin::LOAD_TYPE_STANDALONE;
return JIT\LazyBuiltins::isEnabled($loadType);
}
/**
* Lower a registered ext/* function on first reference (issue #94).
*/
public function ensureJitBuiltinCompiled(string $proxyName): bool
{
foreach ($this->jitBuiltinLookupCandidates($proxyName) as $candidate) {
foreach ($this->modules as $module) {
foreach ($module->getFunctions() as $func) {
if (strtolower($func->getName()) !== $candidate) {
continue;
}
$this->loadJit()->compileFunc($func);
return true;
}
}
}
return false;
}
/**
* @return list<string>
*/
private function jitBuiltinLookupCandidates(string $proxyName): array
{
$lc = strtolower($proxyName);
$candidates = [$lc];
if (preg_match('/^(.+)\\\\([^\\\\]+)::(.+)$/', $lc, $matches)) {
$candidates[] = $matches[2].'::'.$matches[3];
}
if (str_contains($lc, '\\') && !str_contains($lc, '::')) {
$candidates[] = substr($lc, strrpos($lc, '\\') + 1);
}
return array_values(array_unique($candidates));
}
/** Avoid inlining loadJitContext into loadJit (LLVM 9 crash when both are real-lowered #1402). */
private function jitContextForLoadJit(): JITContext {
return $this->loadJitContext();
}
/** `new JIT` crashes LLVM 9 when lowered inside loadJit (#1402); stub until fixed. */
private function createJit(JITContext $context): JIT {
return new JIT($context);
}
/** Nested foreach + compileFunc crashes LLVM 9 when lowered inside loadJit (#1402). */
private function loadJitCompileModuleFuncs(JIT $jit): void {
foreach ($this->modules as $module) {
foreach ($module->getFunctions() as $func) {
$jit->compileFunc($func);
}
}
}
public function loadJitContext(): JITContext {
if (is_null($this->jitContext)) {
$this->jitContext = new JITContext(
$this,
$this->mode === self::MODE_NORMAL ? JIT\Builtin::LOAD_TYPE_EMBED : JIT\Builtin::LOAD_TYPE_STANDALONE
);
if (!is_null($this->debugFile)) {
$this->jitContext->setDebugFile($this->debugFile);
}
foreach ($this->modules as $module) {
$this->jitContext->registerModule($module);
}
}
return $this->jitContext;
}
public function load(Module $module): void {
$this->modules[] = $module;
$module->init($this);
foreach ($module->getFunctions() as $function) {
$this->vmContext->declareFunction($function);
}
}
public function preprocessSourceForParse(string $code, string $filename = 'unknown'): array
{
CurlyBraceOffsetRejector::reject($code, $filename);
$sealedPreprocessor = new SealedClassPreprocessor();
[$code, $permitsByLine] = $sealedPreprocessor->preprocess($code);
$this->sealedClassAnnotator->setPermitsByLine($permitsByLine);
[$code, $this->vmContext->propertyHookRegistry] = (new SourcePreprocessor\PropertyHooks())->process($code);
$code = EnumCaseListRewriter::rewrite($code);
$code = SwitchCommaCaseRewriter::rewrite($code);
$code = GenericArrayTypeSourceRewriter::rewrite($code);
[$code, $abstractEnumLines] = AbstractEnumSourceRewriter::rewrite($code);
$this->abstractEnumMarker->setAbstractLines($abstractEnumLines);
return SourceBareThrowRewriter::rewrite($code);
}
/**
* Source rewrites applied immediately before php-parser / PHPCfg (issue #3243, #4456).
*
* Must run on any path that calls Parser::parse() directly (AOT include discovery, etc.).
*/
public function rewriteSourceBeforeParser(string $code): string
{
$code = AsymmetricVisibilityRewriter::rewrite($code);
$code = InOperatorDesugar::desugar($code);
return PipeOperatorDesugar::desugar($code);
}
public function parse(string $code, string $filename): Script {
[$code, $bareRethrowLines] = $this->preprocessSourceForParse($code, $filename);
$this->compiler->setBareRethrowLines($bareRethrowLines);
$code = $this->rewriteSourceBeforeParser($code);
$fileStrictTypes = $this->detectFileStrictTypes($code);
try {
$script = $this->parser->parse($code, $filename);
} finally {
$this->abstractEnumMarker->clear();
}
$this->preprocessor->traverse($script);
if (!$this->isBootstrapVendorPrelinkMode()) {
$state = new State($script);
$this->typeReconstructor->resolve($state);
}
$this->postprocessor->traverse($script);
$this->detector->detect($script);
// `declare(strict_types=1)` is file-scoped and influences call-site scalar type checks.
// Some parser paths miss the directive when `<?php declare(...)` shares a line (#4411).
if ($fileStrictTypes) {
$script->main->strictTypes = true;
}
return $script;
}
private function detectFileStrictTypes(string $code): bool
{
if (!\function_exists('token_get_all')) {
return false;
}
$tokens = @token_get_all($code);
if (!\is_array($tokens)) {
return false;
}
$i = 0;
$n = \count($tokens);
while ($i < $n) {
$t = $tokens[$i];
$id = \is_array($t) ? $t[0] : null;
if (\in_array($id, [T_OPEN_TAG, T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)) {
++$i;
continue;
}
break;
}
if ($i >= $n) {
return false;
}
$t = $tokens[$i];
if (!\is_array($t) || T_DECLARE !== $t[0]) {
return false;
}
++$i;
while ($i < $n) {
$t = $tokens[$i];
$text = \is_array($t) ? (string) $t[1] : (string) $t;
if ('(' === $text) {
break;
}
++$i;
}
if ($i >= $n) {
return false;
}
++$i; // after '('
$level = 1;
$body = '';
for (; $i < $n; ++$i) {
$t = $tokens[$i];
$text = \is_array($t) ? (string) $t[1] : (string) $t;
if ('(' === $text) {
++$level;
} elseif (')' === $text) {
--$level;
if (0 === $level) {
break;
}
}
if ($level > 0) {
$body .= $text;
}
}
if ('' === $body) {
return false;
}
return (bool) preg_match('/\\bstrict_types\\s*=\\s*1\\b/i', $body);
}
/**
* Log the first CFG-level abort before rethrowing (issue #2642, self-host triage).
*/
private function emitParseCompileFailureStderr(string $sourcePath, \Throwable $e, ?string $sourceCode = null): void
{
$detail = $this->compiler->getCompileAbortDetail();
$primary = null !== $detail && '' !== $detail ? $detail : $e->getMessage();
$this->recordLastParseFailure(sprintf('%s: %s', $sourcePath, $primary));
$line = sprintf("parseAndCompile failure: target=%s: %s\n", $sourcePath, $primary);
$context = null;
if (null !== $sourceCode && $e instanceof \PhpParser\Error) {
$context = $this->formatPhpParserErrorContext($sourceCode, $e);
}
if (\defined('STDERR') && \is_resource(STDERR)) {
fwrite(STDERR, $line);
if (null !== $context && '' !== $context) {
fwrite(STDERR, $context);
}
return;
}
error_log(rtrim($line));
if (null !== $context && '' !== $context) {
error_log(rtrim($context));
}
}
private function formatPhpParserErrorContext(string $sourceCode, \PhpParser\Error $e): ?string
{
// nikic/php-parser messages commonly end with "on line N". Provide a snippet plus
// best-effort mapping to the bundled file marker emitted by SourceBundler.
if (!preg_match('/\\bon line (\\d+)\\b/', $e->getMessage(), $m)) {
return null;
}
$lineNo = (int) $m[1];
if ($lineNo <= 0) {
return null;
}
$lines = preg_split('/\\r\\n|\\n|\\r/', $sourceCode) ?: [];
$idx = $lineNo - 1;
if (!isset($lines[$idx])) {
return null;
}
$marker = null;
for ($i = $idx; $i >= 0; --$i) {
if (\PHPCompiler\Web\SourceBundler::isBundleFileMarker($lines[$i])) {
$marker = trim($lines[$i]);
break;
}
}
$from = max(0, $idx - 4);
$to = min(count($lines) - 1, $idx + 4);
$out = "\n";
if (null !== $marker) {
$out .= " bundle_context: {$marker}\n";
}
$out .= " bundle_snippet:\n";
for ($i = $from; $i <= $to; ++$i) {
$prefix = ($i === $idx) ? '>' : ' ';
$out .= sprintf(" %s %6d | %s\n", $prefix, $i + 1, $lines[$i]);
}
return $out;
}
public function compile(Script $script): ?Block {
/** @var mixed $block */
$block = $this->compiler->compile($script);
if (!$block instanceof Block) {
// Self-host AOT can surface unexpected stub returns as null; preserve a stable abort detail.
$this->compiler->setCompileAbortDetailIfEmpty('Runtime::compile: Compiler::compile returned non-Block');
$sourceFile = $this->compiler->getDebugLastPhaseInputFile() ?? $script->main->getFile();
$this->emitParseAndCompileNullDiagnostic($script, $sourceFile);
return null;
}
$this->assignOpResolver->optimize($block);
return $block;
}
/** M3 native emit: compile trivial scripts via compileEmitSmoke (#1937). */
public function compileEmitSmoke(Script $script): ?Block {
$block = $this->compiler->compileEmitSmoke($script);
if (!$block instanceof Block) {
$this->compiler->setCompileAbortDetailIfEmpty('Runtime::compileEmitSmoke: Compiler::compileEmitSmoke returned non-Block');
$sourceFile = $this->compiler->getDebugLastPhaseInputFile() ?? $script->main->getFile();
$this->emitParseAndCompileNullDiagnostic($script, $sourceFile);
return null;
}
$this->assignOpResolver->optimize($block);
return $block;
}
/** Last parse/compile failure text for native vendor invoker (#3037). */
public static function getLastParseFailure(): ?string
{
return self::$lastParseFailure;
}
/** Instance shim so M3 emit TU can read {@see getLastParseFailure()} via runtimeSpine (#3037). */
public function peekLastParseFailure(): ?string
{
return self::getLastParseFailure();
}
public static function clearLastParseFailure(): void
{
self::$lastParseFailure = null;
}
/**
* Record compile-null detail when parse+compile are split (M3 emit TU bridge, #3037).
*/
public function noteParseCompileNullForScript(?Script $script): void
{
$this->recordLastParseFailure($this->formatParseAndCompileNullDetail($script));
}
private function recordLastParseFailure(?string $detail): void
{
if (null !== $detail && '' !== $detail) {
self::$lastParseFailure = $detail;
}
}
public function parseAndCompileEmitSmoke(string $code, string $filename): ?Block
{
self::clearLastParseFailure();
$this->compiler->resetCompileAbortDetail();
$this->compiler->setDebugLastPhaseInputFile($filename);
try {
$script = $this->parse($code, $filename);
$block = $this->compileEmitSmoke($script);
if (null !== $block) {
$block->setScriptPath($filename);
}
return $block;
} catch (\Throwable $e) {
$this->emitParseCompileFailureStderr($filename, $e, $code);
throw $e;
}
}
public function compileFunc(string $name, CfgFunc $func): Func {
$compiled = $this->compiler->compileFunc($name, $func);
$this->assignOpResolver->optimize($compiled->block);
return $compiled;
}
public function jit(?Block $block, ?string $sourceCode = null, ?string $sourcePath = null) {
$this->jitLoadedFromDiskCache = false;
$this->jitCompileCacheKey = null;
if (
null !== $block
&& is_string($sourceCode)
&& is_string($sourcePath)
&& JIT\CompileCache::isEnabled()
) {
$cacheKey = JIT\CompileCache::computeKey($sourcePath, $sourceCode);
$this->jitCompileCacheKey = $cacheKey;
if (JIT\CompileCache::isFresh($cacheKey, $sourcePath, $sourceCode)) {
$context = $this->loadJitContext();
if (JIT\CompileCache::tryRestore($context, $block, $cacheKey)) {
$this->jitLoadedFromDiskCache = true;
}
}
if (!$this->jitLoadedFromDiskCache) {
JIT\CompileCache::beginRecording($cacheKey);
}
}
if (!$this->jitLoadedFromDiskCache) {
$this->jitCompileBlock($block);
}
$this->jitEmitInPlace();
if (
!$this->jitLoadedFromDiskCache
&& null !== $this->jitCompileCacheKey
&& null !== $this->jitContext
) {
JIT\CompileCache::save($this->jitContext, $this->jitCompileCacheKey);
}
JIT\CompileCache::finishRecording();
}
/** Lower script block to LLVM IR (issue #1898 bench-compile phases). */
public function jitCompileBlock(?Block $block): void {
$this->loadJit()->compile($block);
}
/** MCJIT link / engine creation; no-op when already compiled in-process (#153 warm). */
public function jitEmitInPlace(): void {
if ($this->jitLoadedFromDiskCache) {
$this->loadJitContext()->compileInPlaceFromDiskCache();
} else {
$this->loadJitContext()->compileInPlace();
}
}
public function standalone(?Block $block, string $outfile, ?string $sourceCode = null, ?string $sourceFilename = null) {
\PHPCompiler\JIT\Progress::noteFunction('runtime_standalone_begin');
$context = $this->loadJitContext();
if (null !== $sourceFilename && '' !== $sourceFilename) {
$context->setAotSourceFilename($sourceFilename);
}
\PHPCompiler\JIT\Progress::noteFunction('runtime_standalone_loadjitcontext_done');
// Generator bodies use GeneratorHelper resume lowering; script-scope yield still blocked (#3115).
if (null !== $block && Block::containsGeneratorOpcodesInScriptScope($block)) {
throw new \LogicException('yield in the main script is not supported in AOT yet (issue #3115).');
}
$context->setMain($this->loadJit()->compile($block));
\PHPCompiler\JIT\Progress::noteFunction('runtime_standalone_compile_done');
$context->compileToFile($outfile);
\PHPCompiler\JIT\Progress::noteFunction('runtime_standalone_compiletofile_done');
}
public function parseAndCompile(string $code, string $filename): ?Block {
self::clearLastParseFailure();
$this->compiler->resetCompileAbortDetail();
$this->compiler->setDebugLastPhaseInputFile($filename);
\PHPCompiler\JIT\Progress::notePhase('runtime_parseandcompile_begin');
\PHPCompiler\JIT\Progress::noteEntry($filename);
try {
$script = $this->parse($code, $filename);
$block = $this->compile($script);
if (null !== $block) {
$block->setScriptPath($filename);
}
return $block;
} catch (\Throwable $e) {
$this->emitParseCompileFailureStderr($filename, $e, $code);
throw $e;
}
}
public function parseAndCompileFile(string $filename): ?Block {
self::clearLastParseFailure();
$this->compiler->resetCompileAbortDetail();
try {
$normalized = VM\ScriptStack::normalize($filename);
if ('' !== $normalized) {
$filename = $normalized;
}
$this->compiler->setDebugLastPhaseInputFile($filename);
\PHPCompiler\JIT\Progress::notePhase('runtime_parseandcompilefile_begin');
\PHPCompiler\JIT\Progress::noteEntry($filename);
\PHPCompiler\JIT\Progress::noteFunction('runtime_parseandcompilefile_read_begin');
$code = (string) file_get_contents($filename);
\PHPCompiler\JIT\Progress::noteFunction('runtime_parseandcompilefile_read_done');
$script = $this->parse($code, $filename);
\PHPCompiler\JIT\Progress::noteFunction('runtime_parseandcompilefile_parse_done');
$block = $this->compile($script);
\PHPCompiler\JIT\Progress::noteFunction('runtime_parseandcompilefile_compile_done');
if (null !== $block) {
$block->setScriptPath($filename);
}
return $block;
} catch (\Throwable $e) {
$this->emitParseCompileFailureStderr($filename, $e, isset($code) ? $code : null);
throw $e;
}
}
/**
* Human detail for `parseAndCompile()` / emit-smoke returning null (#2642, #2633).
*
* Prefer compile abort detail from the real compiler; otherwise lint the parsed script.
*/
public function formatParseAndCompileNullDetail(?Script $script): ?string
{
$detail = $this->compiler->getCompileAbortDetail();
if (null !== $detail && '' !== $detail) {
return $detail;
}
if (null === $script) {
return 'parse returned null';
}
$lint = new LintCompiler();
$prev = $this->compiler;
$this->compiler = $lint;
try {
$this->compile($script);
} catch (\Throwable $e) {
// parse/type failure — lint may still have recorded an issue.
} finally {
$this->compiler = $prev;
}
$issue = $lint->issues[0] ?? null;
return null !== $issue ? $issue->formatHuman() : null;
}
/**
* `parseAndCompile()` returning null is a common self-host bootstrap failure mode (#2642).
* Best-effort: re-run compile under the lint compiler and print the first unsupported kind.
*/
private function emitParseAndCompileNullDiagnostic(Script $script, ?string $sourceFile = null): void
{
$detail = $this->formatParseAndCompileNullDetail($script);
$this->recordLastParseFailure($detail);
if (!self::isParseDiagEnabled()) {
return;
}
if (null === $detail || '' === $detail) {
$detail = 'unknown compile failure (no lint issue recorded)';
}
if (null === $sourceFile || '' === $sourceFile) {
$sourceFile = $script->main->getFile();
}
if ('' === $sourceFile) {
$sourceFile = 'unknown';
}
$line = sprintf("parseAndCompile: %s: %s\n", $sourceFile, $detail);
if (\defined('STDERR') && \is_resource(STDERR)) {
fwrite(STDERR, $line);
return;
}
echo $line;
}
/**
* Refresh JIT sg_* tables from VM / CGI env before each run (issue #642).
*/
public function syncJitSuperglobals(
?string $queryString = null,
?string $postBody = null,
?string $scriptFilename = null
): void {
Superglobals::populateFromEnvironment(
$this->vmContext,
$queryString,
$postBody,
$scriptFilename
);
if (null !== $this->jitContext) {
$this->jitContext->refreshSuperglobals();
}
}
public function run(?Block $block) {
$this->ensureVm();
Superglobals::setActiveContext($this->vmContext);
try {
return $this->vm->run($block);
} finally {
ShutdownQueue::run($this->vmContext);
OutputBuffer::endAllAtShutdown();
Superglobals::setActiveContext(null);
}
}
}