-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBytecodeCompiler.cpp
983 lines (812 loc) · 33 KB
/
BytecodeCompiler.cpp
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "frontend/BytecodeCompiler.h"
#include "mozilla/Attributes.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Maybe.h"
#include "mozilla/Utf8.h" // mozilla::Utf8Unit
#include "builtin/ModuleObject.h"
#include "frontend/BytecodeCompilation.h"
#include "frontend/BytecodeEmitter.h"
#include "frontend/EitherParser.h"
#include "frontend/ErrorReporter.h"
#include "frontend/FoldConstants.h"
#ifdef JS_ENABLE_SMOOSH
# include "frontend/Frontend2.h" // Smoosh
#endif
#include "frontend/ModuleSharedContext.h"
#include "frontend/Parser.h"
#include "js/SourceText.h"
#include "vm/GeneratorAndAsyncKind.h" // js::GeneratorKind, js::FunctionAsyncKind
#include "vm/GlobalObject.h"
#include "vm/JSContext.h"
#include "vm/JSScript.h"
#include "vm/ModuleBuilder.h" // js::ModuleBuilder
#include "vm/TraceLogging.h"
#include "wasm/AsmJS.h"
#include "debugger/DebugAPI-inl.h" // DebugAPI
#include "vm/EnvironmentObject-inl.h"
#include "vm/GeckoProfiler-inl.h"
#include "vm/JSContext-inl.h"
using namespace js;
using namespace js::frontend;
using mozilla::Maybe;
using mozilla::Nothing;
using mozilla::Utf8Unit;
using JS::CompileOptions;
using JS::ReadOnlyCompileOptions;
using JS::SourceText;
// RAII class to check the frontend reports an exception when it fails to
// compile a script.
class MOZ_RAII AutoAssertReportedException {
#ifdef DEBUG
JSContext* cx_;
bool check_;
public:
explicit AutoAssertReportedException(JSContext* cx) : cx_(cx), check_(true) {}
void reset() { check_ = false; }
~AutoAssertReportedException() {
if (!check_) {
return;
}
if (!cx_->isHelperThreadContext()) {
MOZ_ASSERT(cx_->isExceptionPending());
return;
}
ParseTask* task = cx_->parseTask();
MOZ_ASSERT(task->outOfMemory || task->overRecursed ||
!task->errors.empty());
}
#else
public:
explicit AutoAssertReportedException(JSContext*) {}
void reset() {}
#endif
};
static bool EmplaceEmitter(CompilationInfo& compilationInfo,
Maybe<BytecodeEmitter>& emitter,
const EitherParser& parser, SharedContext* sc);
template <typename Unit>
class MOZ_STACK_CLASS frontend::SourceAwareCompiler {
protected:
SourceText<Unit>& sourceBuffer_;
Maybe<Parser<SyntaxParseHandler, Unit>> syntaxParser;
Maybe<Parser<FullParseHandler, Unit>> parser;
using TokenStreamPosition = frontend::TokenStreamPosition<Unit>;
protected:
explicit SourceAwareCompiler(SourceText<Unit>& sourceBuffer)
: sourceBuffer_(sourceBuffer) {
MOZ_ASSERT(sourceBuffer_.get() != nullptr);
}
// Call this before calling compile{Global,Eval}Script.
MOZ_MUST_USE bool createSourceAndParser(LifoAllocScope& allocScope,
CompilationInfo& compilationInfo);
void assertSourceAndParserCreated(CompilationInfo& compilationInfo) const {
MOZ_ASSERT(compilationInfo.sourceObject != nullptr);
MOZ_ASSERT(compilationInfo.sourceObject->source() != nullptr);
MOZ_ASSERT(parser.isSome());
}
void assertSourceParserAndScriptCreated(CompilationInfo& compilationInfo) {
assertSourceAndParserCreated(compilationInfo);
}
MOZ_MUST_USE bool emplaceEmitter(CompilationInfo& compilationInfo,
Maybe<BytecodeEmitter>& emitter,
SharedContext* sharedContext) {
return EmplaceEmitter(compilationInfo, emitter, EitherParser(parser.ptr()),
sharedContext);
}
bool canHandleParseFailure(CompilationInfo& compilationInfo,
const Directives& newDirectives);
void handleParseFailure(CompilationInfo& compilationInfo,
const Directives& newDirectives,
TokenStreamPosition& startPosition,
CompilationInfo::RewindToken& startObj);
};
template <typename Unit>
class MOZ_STACK_CLASS frontend::ScriptCompiler
: public SourceAwareCompiler<Unit> {
using Base = SourceAwareCompiler<Unit>;
protected:
using Base::parser;
using Base::sourceBuffer_;
using Base::assertSourceParserAndScriptCreated;
using Base::canHandleParseFailure;
using Base::emplaceEmitter;
using Base::handleParseFailure;
using typename Base::TokenStreamPosition;
public:
explicit ScriptCompiler(SourceText<Unit>& srcBuf) : Base(srcBuf) {}
using Base::createSourceAndParser;
JSScript* compileScript(CompilationInfo& compilationInfo, SharedContext* sc);
};
/* If we're on main thread, tell the Debugger about a newly compiled script.
*
* See: finishSingleParseTask/finishMultiParseTask for the off-thread case.
*/
static void tellDebuggerAboutCompiledScript(JSContext* cx, bool hideScript,
Handle<JSScript*> script) {
if (cx->isHelperThreadContext()) {
return;
}
// If hideScript then script may not be ready to be interrogated by the
// debugger.
if (!hideScript) {
DebugAPI::onNewScript(cx, script);
}
}
template <typename Unit>
static JSScript* CreateGlobalScript(CompilationInfo& compilationInfo,
GlobalSharedContext& globalsc,
JS::SourceText<Unit>& srcBuf) {
AutoAssertReportedException assertException(compilationInfo.cx);
LifoAllocScope allocScope(&compilationInfo.cx->tempLifoAlloc());
frontend::ScriptCompiler<Unit> compiler(srcBuf);
if (!compiler.createSourceAndParser(allocScope, compilationInfo)) {
return nullptr;
}
if (!compiler.compileScript(compilationInfo, &globalsc)) {
return nullptr;
}
tellDebuggerAboutCompiledScript(
compilationInfo.cx, compilationInfo.options.hideScriptFromDebugger,
compilationInfo.script);
assertException.reset();
return compilationInfo.script;
}
JSScript* frontend::CompileGlobalScript(CompilationInfo& compilationInfo,
GlobalSharedContext& globalsc,
JS::SourceText<char16_t>& srcBuf) {
return CreateGlobalScript(compilationInfo, globalsc, srcBuf);
}
JSScript* frontend::CompileGlobalScript(CompilationInfo& compilationInfo,
GlobalSharedContext& globalsc,
JS::SourceText<Utf8Unit>& srcBuf) {
#ifdef JS_ENABLE_SMOOSH
if (compilationInfo.cx->options().trySmoosh()) {
bool unimplemented = false;
JSContext* cx = compilationInfo.cx;
JSRuntime* rt = cx->runtime();
auto script =
Smoosh::compileGlobalScript(compilationInfo, srcBuf, &unimplemented);
if (!unimplemented) {
if (compilationInfo.cx->options().trackNotImplemented()) {
rt->parserWatcherFile.put("1");
}
return script;
}
if (compilationInfo.cx->options().trackNotImplemented()) {
rt->parserWatcherFile.put("0");
}
fprintf(stderr, "Falling back!\n");
}
#endif // JS_ENABLE_SMOOSH
return CreateGlobalScript(compilationInfo, globalsc, srcBuf);
}
template <typename Unit>
static JSScript* CreateEvalScript(CompilationInfo& compilationInfo,
EvalSharedContext& evalsc,
SourceText<Unit>& srcBuf) {
AutoAssertReportedException assertException(compilationInfo.cx);
LifoAllocScope allocScope(&compilationInfo.cx->tempLifoAlloc());
frontend::ScriptCompiler<Unit> compiler(srcBuf);
if (!compiler.createSourceAndParser(allocScope, compilationInfo)) {
return nullptr;
}
if (!compiler.compileScript(compilationInfo, &evalsc)) {
return nullptr;
}
tellDebuggerAboutCompiledScript(
compilationInfo.cx, compilationInfo.options.hideScriptFromDebugger,
compilationInfo.script);
assertException.reset();
return compilationInfo.script;
}
JSScript* frontend::CompileEvalScript(CompilationInfo& compilationInfo,
EvalSharedContext& evalsc,
JS::SourceText<char16_t>& srcBuf) {
return CreateEvalScript(compilationInfo, evalsc, srcBuf);
}
template <typename Unit>
class MOZ_STACK_CLASS frontend::ModuleCompiler final
: public SourceAwareCompiler<Unit> {
using Base = SourceAwareCompiler<Unit>;
using Base::assertSourceParserAndScriptCreated;
using Base::createSourceAndParser;
using Base::emplaceEmitter;
using Base::parser;
public:
explicit ModuleCompiler(SourceText<Unit>& srcBuf) : Base(srcBuf) {}
ModuleObject* compile(CompilationInfo& compilationInfo);
};
template <typename Unit>
class MOZ_STACK_CLASS frontend::StandaloneFunctionCompiler final
: public SourceAwareCompiler<Unit> {
using Base = SourceAwareCompiler<Unit>;
using Base::assertSourceAndParserCreated;
using Base::canHandleParseFailure;
using Base::emplaceEmitter;
using Base::handleParseFailure;
using Base::parser;
using Base::sourceBuffer_;
using typename Base::TokenStreamPosition;
public:
explicit StandaloneFunctionCompiler(SourceText<Unit>& srcBuf)
: Base(srcBuf) {}
using Base::createSourceAndParser;
FunctionNode* parse(CompilationInfo& compilationInfo,
FunctionSyntaxKind syntaxKind,
GeneratorKind generatorKind, FunctionAsyncKind asyncKind,
const Maybe<uint32_t>& parameterListEnd);
JSFunction* compile(CompilationInfo& info, FunctionNode* parsedFunction);
};
AutoFrontendTraceLog::AutoFrontendTraceLog(JSContext* cx,
const TraceLoggerTextId id,
const ErrorReporter& errorReporter)
#ifdef JS_TRACE_LOGGING
: logger_(TraceLoggerForCurrentThread(cx)) {
if (!logger_) {
return;
}
// If the tokenizer hasn't yet gotten any tokens, use the line and column
// numbers from CompileOptions.
uint32_t line, column;
if (errorReporter.hasTokenizationStarted()) {
line = errorReporter.options().lineno;
column = errorReporter.options().column;
} else {
errorReporter.currentLineAndColumn(&line, &column);
}
frontendEvent_.emplace(TraceLogger_Frontend, errorReporter.getFilename(),
line, column);
frontendLog_.emplace(logger_, *frontendEvent_);
typeLog_.emplace(logger_, id);
}
#else
{
}
#endif
AutoFrontendTraceLog::AutoFrontendTraceLog(JSContext* cx,
const TraceLoggerTextId id,
const ErrorReporter& errorReporter,
FunctionBox* funbox)
#ifdef JS_TRACE_LOGGING
: logger_(TraceLoggerForCurrentThread(cx)) {
if (!logger_) {
return;
}
frontendEvent_.emplace(TraceLogger_Frontend, errorReporter.getFilename(),
funbox->extent().lineno, funbox->extent().column);
frontendLog_.emplace(logger_, *frontendEvent_);
typeLog_.emplace(logger_, id);
}
#else
{
}
#endif
AutoFrontendTraceLog::AutoFrontendTraceLog(JSContext* cx,
const TraceLoggerTextId id,
const ErrorReporter& errorReporter,
ParseNode* pn)
#ifdef JS_TRACE_LOGGING
: logger_(TraceLoggerForCurrentThread(cx)) {
if (!logger_) {
return;
}
uint32_t line, column;
errorReporter.lineAndColumnAt(pn->pn_pos.begin, &line, &column);
frontendEvent_.emplace(TraceLogger_Frontend, errorReporter.getFilename(),
line, column);
frontendLog_.emplace(logger_, *frontendEvent_);
typeLog_.emplace(logger_, id);
}
#else
{
}
#endif
static bool CanLazilyParse(const CompilationInfo& compilationInfo) {
return !compilationInfo.options.discardSource &&
!compilationInfo.options.sourceIsLazy &&
!compilationInfo.options.forceFullParse();
}
template <typename Unit>
bool frontend::SourceAwareCompiler<Unit>::createSourceAndParser(
LifoAllocScope& allocScope, CompilationInfo& compilationInfo) {
if (!compilationInfo.assignSource(sourceBuffer_)) {
return false;
}
if (CanLazilyParse(compilationInfo)) {
syntaxParser.emplace(compilationInfo.cx, compilationInfo.options,
sourceBuffer_.units(), sourceBuffer_.length(),
/* foldConstants = */ false, compilationInfo, nullptr,
nullptr);
if (!syntaxParser->checkOptions()) {
return false;
}
}
parser.emplace(compilationInfo.cx, compilationInfo.options,
sourceBuffer_.units(), sourceBuffer_.length(),
/* foldConstants = */ true, compilationInfo,
syntaxParser.ptrOr(nullptr), nullptr);
parser->ss = compilationInfo.sourceObject->source();
return parser->checkOptions();
}
static bool EmplaceEmitter(CompilationInfo& compilationInfo,
Maybe<BytecodeEmitter>& emitter,
const EitherParser& parser, SharedContext* sc) {
BytecodeEmitter::EmitterMode emitterMode =
sc->selfHosted() ? BytecodeEmitter::SelfHosting : BytecodeEmitter::Normal;
emitter.emplace(/* parent = */ nullptr, parser, sc, compilationInfo,
emitterMode);
return emitter->init();
}
template <typename Unit>
bool frontend::SourceAwareCompiler<Unit>::canHandleParseFailure(
CompilationInfo& compilationInfo, const Directives& newDirectives) {
// Try to reparse if no parse errors were thrown and the directives changed.
//
// NOTE:
// Only the following two directive changes force us to reparse the script:
// - The "use asm" directive was encountered.
// - The "use strict" directive was encountered and duplicate parameter names
// are present. We reparse in this case to display the error at the correct
// source location. See |Parser::hasValidSimpleStrictParameterNames()|.
return !parser->anyChars.hadError() &&
compilationInfo.directives != newDirectives;
}
template <typename Unit>
void frontend::SourceAwareCompiler<Unit>::handleParseFailure(
CompilationInfo& compilationInfo, const Directives& newDirectives,
TokenStreamPosition& startPosition,
CompilationInfo::RewindToken& startObj) {
MOZ_ASSERT(canHandleParseFailure(compilationInfo, newDirectives));
// Rewind to starting position to retry.
parser->tokenStream.rewind(startPosition);
compilationInfo.rewind(startObj);
// Assignment must be monotonic to prevent reparsing iloops
MOZ_ASSERT_IF(compilationInfo.directives.strict(), newDirectives.strict());
MOZ_ASSERT_IF(compilationInfo.directives.asmJS(), newDirectives.asmJS());
compilationInfo.directives = newDirectives;
}
template <typename Unit>
JSScript* frontend::ScriptCompiler<Unit>::compileScript(
CompilationInfo& compilationInfo, SharedContext* sc) {
assertSourceParserAndScriptCreated(compilationInfo);
TokenStreamPosition startPosition(compilationInfo.keepAtoms,
parser->tokenStream);
JSContext* cx = compilationInfo.cx;
ParseNode* pn;
{
AutoGeckoProfilerEntry pseudoFrame(cx, "script parsing",
JS::ProfilingCategoryPair::JS_Parsing);
if (sc->isEvalContext()) {
pn = parser->evalBody(sc->asEvalContext());
} else {
pn = parser->globalBody(sc->asGlobalContext());
}
}
if (!pn) {
// Global and eval scripts don't get reparsed after a new directive was
// encountered:
// - "use strict" doesn't require any special error reporting for scripts.
// - "use asm" directives don't have an effect in global/eval contexts.
MOZ_ASSERT(
!canHandleParseFailure(compilationInfo, compilationInfo.directives));
return nullptr;
}
{
// Successfully parsed. Emit the script.
AutoGeckoProfilerEntry pseudoFrame(cx, "script emit",
JS::ProfilingCategoryPair::JS_Parsing);
Maybe<BytecodeEmitter> emitter;
if (!emplaceEmitter(compilationInfo, emitter, sc)) {
return nullptr;
}
if (!emitter->emitScript(pn)) {
return nullptr;
}
if (!compilationInfo.instantiateStencils()) {
return nullptr;
}
MOZ_ASSERT(compilationInfo.script);
}
// We have just finished parsing the source. Inform the source so that we
// can compute statistics (e.g. how much time our functions remain lazy).
compilationInfo.sourceObject->source()->recordParseEnded();
// Enqueue an off-thread source compression task after finishing parsing.
if (!compilationInfo.sourceObject->source()->tryCompressOffThread(cx)) {
return nullptr;
}
MOZ_ASSERT_IF(!cx->isHelperThreadContext(), !cx->isExceptionPending());
return compilationInfo.script;
}
template <typename Unit>
ModuleObject* frontend::ModuleCompiler<Unit>::compile(
CompilationInfo& compilationInfo) {
if (!createSourceAndParser(compilationInfo.allocScope, compilationInfo)) {
return nullptr;
}
JSContext* cx = compilationInfo.cx;
Rooted<ModuleObject*> module(cx, ModuleObject::create(cx));
if (!module) {
return nullptr;
}
ModuleBuilder builder(cx, parser.ptr());
RootedScope enclosingScope(cx, &cx->global()->emptyGlobalScope());
uint32_t len = this->sourceBuffer_.length();
SourceExtent extent =
SourceExtent::makeGlobalExtent(len, compilationInfo.options);
ModuleSharedContext modulesc(cx, module, compilationInfo, enclosingScope,
builder, extent);
ParseNode* pn = parser->moduleBody(&modulesc);
if (!pn) {
return nullptr;
}
Maybe<BytecodeEmitter> emitter;
if (!emplaceEmitter(compilationInfo, emitter, &modulesc)) {
return nullptr;
}
if (!emitter->emitScript(pn->as<ModuleNode>().body())) {
return nullptr;
}
if (!compilationInfo.instantiateStencils()) {
return nullptr;
}
MOZ_ASSERT(compilationInfo.script);
if (!builder.initModule(module)) {
return nullptr;
}
module->initScriptSlots(compilationInfo.script);
module->initStatusSlot();
if (!ModuleObject::createEnvironment(cx, module)) {
return nullptr;
}
// Enqueue an off-thread source compression task after finishing parsing.
if (!compilationInfo.sourceObject->source()->tryCompressOffThread(cx)) {
return nullptr;
}
MOZ_ASSERT_IF(!cx->isHelperThreadContext(), !cx->isExceptionPending());
return module;
}
// Parse a standalone JS function, which might appear as the value of an
// event handler attribute in an HTML <INPUT> tag, or in a Function()
// constructor.
template <typename Unit>
FunctionNode* frontend::StandaloneFunctionCompiler<Unit>::parse(
CompilationInfo& compilationInfo, FunctionSyntaxKind syntaxKind,
GeneratorKind generatorKind, FunctionAsyncKind asyncKind,
const Maybe<uint32_t>& parameterListEnd) {
assertSourceAndParserCreated(compilationInfo);
TokenStreamPosition startPosition(compilationInfo.keepAtoms,
parser->tokenStream);
CompilationInfo::RewindToken startObj = compilationInfo.getRewindToken();
// Speculatively parse using the default directives implied by the context.
// If a directive is encountered (e.g., "use strict") that changes how the
// function should have been parsed, we backup and reparse with the new set
// of directives.
FunctionNode* fn;
for (;;) {
Directives newDirectives = compilationInfo.directives;
fn = parser->standaloneFunction(parameterListEnd, syntaxKind, generatorKind,
asyncKind, compilationInfo.directives,
&newDirectives);
if (fn) {
break;
}
// Maybe we encountered a new directive. See if we can try again.
if (!canHandleParseFailure(compilationInfo, newDirectives)) {
return nullptr;
}
handleParseFailure(compilationInfo, newDirectives, startPosition, startObj);
}
return fn;
}
// Compile a standalone JS function.
template <typename Unit>
JSFunction* frontend::StandaloneFunctionCompiler<Unit>::compile(
CompilationInfo& compilationInfo, FunctionNode* parsedFunction) {
FunctionBox* funbox = parsedFunction->funbox();
if (funbox->isInterpreted()) {
MOZ_ASSERT(funbox->function() == nullptr);
Maybe<BytecodeEmitter> emitter;
if (!emplaceEmitter(compilationInfo, emitter, funbox)) {
return nullptr;
}
if (!emitter->emitFunctionScript(parsedFunction, TopLevelFunction::Yes)) {
return nullptr;
}
// The parser extent has stripped off the leading `function...` but
// we want the SourceExtent used in the final standalone script to
// start from the beginning of the buffer, and use the provided
// line and column.
compilationInfo.topLevel.get().extent =
SourceExtent{/* sourceStart = */ 0,
sourceBuffer_.length(),
funbox->extent().toStringStart,
funbox->extent().toStringEnd,
compilationInfo.options.lineno,
compilationInfo.options.column};
} else {
// The asm.js module was created by parser. Instantiation below will
// allocate the JSFunction that wraps it.
MOZ_ASSERT(funbox->isAsmJSModule());
MOZ_ASSERT(compilationInfo.asmJS.has(funbox->index()));
compilationInfo.topLevel.get().isAsmJSModule = true;
funbox->copyScriptFields(compilationInfo.topLevel.get());
}
if (!compilationInfo.instantiateStencils()) {
return nullptr;
}
MOZ_ASSERT(funbox->function()->hasBytecode() ||
IsAsmJSModule(funbox->function()));
// Enqueue an off-thread source compression task after finishing parsing.
if (!compilationInfo.sourceObject->source()->tryCompressOffThread(
compilationInfo.cx)) {
return nullptr;
}
return funbox->function();
}
ScriptSourceObject* frontend::CreateScriptSourceObject(
JSContext* cx, const ReadOnlyCompileOptions& options) {
ScriptSource* ss = cx->new_<ScriptSource>();
if (!ss) {
return nullptr;
}
ScriptSourceHolder ssHolder(ss);
if (!ss->initFromOptions(cx, options)) {
return nullptr;
}
RootedScriptSourceObject sso(cx, ScriptSourceObject::create(cx, ss));
if (!sso) {
return nullptr;
}
// Off-thread compilations do all their GC heap allocation, including the
// SSO, in a temporary compartment. Hence, for the SSO to refer to the
// gc-heap-allocated values in |options|, it would need cross-compartment
// wrappers from the temporary compartment to the real compartment --- which
// would then be inappropriate once we merged the temporary and real
// compartments.
//
// Instead, we put off populating those SSO slots in off-thread compilations
// until after we've merged compartments.
if (!cx->isHelperThreadContext()) {
if (!ScriptSourceObject::initFromOptions(cx, sso, options)) {
return nullptr;
}
}
return sso;
}
template <typename Unit>
static ModuleObject* InternalParseModule(
JSContext* cx, const ReadOnlyCompileOptions& optionsInput,
SourceText<Unit>& srcBuf, ScriptSourceObject** sourceObjectOut) {
MOZ_ASSERT(srcBuf.get());
MOZ_ASSERT_IF(sourceObjectOut, *sourceObjectOut == nullptr);
AutoAssertReportedException assertException(cx);
CompileOptions options(cx, optionsInput);
options.setForceStrictMode(); // ES6 10.2.1 Module code is always strict mode
// code.
options.setIsRunOnce(true);
options.allowHTMLComments = false;
LifoAllocScope allocScope(&cx->tempLifoAlloc());
CompilationInfo compilationInfo(cx, allocScope, options);
if (!compilationInfo.init(cx)) {
return nullptr;
}
if (sourceObjectOut) {
*sourceObjectOut = compilationInfo.sourceObject;
}
ModuleCompiler<Unit> compiler(srcBuf);
Rooted<ModuleObject*> module(cx, compiler.compile(compilationInfo));
if (!module) {
return nullptr;
}
tellDebuggerAboutCompiledScript(cx, options.hideScriptFromDebugger,
compilationInfo.script);
assertException.reset();
return module;
}
ModuleObject* frontend::ParseModule(JSContext* cx,
const ReadOnlyCompileOptions& optionsInput,
SourceText<char16_t>& srcBuf,
ScriptSourceObject** sourceObjectOut) {
return InternalParseModule(cx, optionsInput, srcBuf, sourceObjectOut);
}
ModuleObject* frontend::ParseModule(JSContext* cx,
const ReadOnlyCompileOptions& optionsInput,
SourceText<Utf8Unit>& srcBuf,
ScriptSourceObject** sourceObjectOut) {
return InternalParseModule(cx, optionsInput, srcBuf, sourceObjectOut);
}
template <typename Unit>
static ModuleObject* CreateModule(JSContext* cx,
const JS::ReadOnlyCompileOptions& options,
SourceText<Unit>& srcBuf) {
AutoAssertReportedException assertException(cx);
if (!GlobalObject::ensureModulePrototypesCreated(cx, cx->global())) {
return nullptr;
}
RootedModuleObject module(cx, ParseModule(cx, options, srcBuf, nullptr));
if (!module) {
return nullptr;
}
// This happens in GlobalHelperThreadState::finishModuleParseTask() when a
// module is compiled off thread.
if (!ModuleObject::Freeze(cx, module)) {
return nullptr;
}
assertException.reset();
return module;
}
ModuleObject* frontend::CompileModule(JSContext* cx,
const JS::ReadOnlyCompileOptions& options,
SourceText<char16_t>& srcBuf) {
return CreateModule(cx, options, srcBuf);
}
ModuleObject* frontend::CompileModule(JSContext* cx,
const JS::ReadOnlyCompileOptions& options,
SourceText<Utf8Unit>& srcBuf) {
return CreateModule(cx, options, srcBuf);
}
template <typename Unit>
static bool CompileLazyFunctionImpl(JSContext* cx, Handle<BaseScript*> lazy,
const Unit* units, size_t length) {
MOZ_ASSERT(cx->compartment() == lazy->compartment());
// We can only compile functions whose parents have previously been
// compiled, because compilation requires full information about the
// function's immediately enclosing scope.
MOZ_ASSERT(lazy->isReadyForDelazification());
AutoAssertReportedException assertException(cx);
Rooted<JSFunction*> fun(cx, lazy->function());
JS::CompileOptions options(cx);
options.setMutedErrors(lazy->mutedErrors())
.setFileAndLine(lazy->filename(), lazy->lineno())
.setColumn(lazy->column())
.setScriptSourceOffset(lazy->sourceStart())
.setNoScriptRval(false)
.setSelfHostingMode(false);
// Update statistics to find out if we are delazifying just after having
// lazified. Note that we are interested in the delta between end of
// syntax parsing and start of full parsing, so we do this now rather than
// after parsing below.
if (!lazy->scriptSource()->parseEnded().IsNull()) {
const mozilla::TimeDuration delta =
ReallyNow() - lazy->scriptSource()->parseEnded();
// Differentiate between web-facing and privileged code, to aid
// with optimization. Due to the number of calls to this function,
// we use `cx->runningWithTrustedPrincipals`, which is fast but
// will classify addons alongside with web-facing code.
const int HISTOGRAM =
cx->runningWithTrustedPrincipals()
? JS_TELEMETRY_PRIVILEGED_PARSER_COMPILE_LAZY_AFTER_MS
: JS_TELEMETRY_WEB_PARSER_COMPILE_LAZY_AFTER_MS;
cx->runtime()->addTelemetry(HISTOGRAM, delta.ToMilliseconds());
}
LifoAllocScope allocScope(&cx->tempLifoAlloc());
CompilationInfo compilationInfo(cx, allocScope, options,
fun->enclosingScope());
compilationInfo.initFromLazy(lazy);
Parser<FullParseHandler, Unit> parser(cx, options, units, length,
/* foldConstants = */ true,
compilationInfo, nullptr, lazy);
if (!parser.checkOptions()) {
return false;
}
AutoGeckoProfilerEntry pseudoFrame(cx, "script delazify",
JS::ProfilingCategoryPair::JS_Parsing);
FunctionNode* pn =
parser.standaloneLazyFunction(fun, lazy->toStringStart(), lazy->strict(),
lazy->generatorKind(), lazy->asyncKind());
if (!pn) {
return false;
}
mozilla::DebugOnly<uint32_t> lazyFlags =
static_cast<uint32_t>(lazy->immutableFlags());
BytecodeEmitter bce(/* parent = */ nullptr, &parser, pn->funbox(),
compilationInfo, BytecodeEmitter::LazyFunction);
if (!bce.init(pn->pn_pos)) {
return false;
}
if (!bce.emitFunctionScript(pn, TopLevelFunction::Yes)) {
return false;
}
if (!compilationInfo.instantiateStencils()) {
return false;
}
MOZ_ASSERT(lazyFlags == compilationInfo.script->immutableFlags());
MOZ_ASSERT(compilationInfo.script->outermostScope()->hasOnChain(
ScopeKind::NonSyntactic) ==
compilationInfo.script->immutableFlags().hasFlag(
JSScript::ImmutableFlags::HasNonSyntacticScope));
assertException.reset();
return true;
}
bool frontend::CompileLazyFunction(JSContext* cx, Handle<BaseScript*> lazy,
const char16_t* units, size_t length) {
return CompileLazyFunctionImpl(cx, lazy, units, length);
}
bool frontend::CompileLazyFunction(JSContext* cx, Handle<BaseScript*> lazy,
const Utf8Unit* units, size_t length) {
return CompileLazyFunctionImpl(cx, lazy, units, length);
}
static JSFunction* CompileStandaloneFunction(
JSContext* cx, const JS::ReadOnlyCompileOptions& options,
JS::SourceText<char16_t>& srcBuf, const Maybe<uint32_t>& parameterListEnd,
FunctionSyntaxKind syntaxKind, GeneratorKind generatorKind,
FunctionAsyncKind asyncKind, HandleScope enclosingScope = nullptr) {
AutoAssertReportedException assertException(cx);
RootedScope scope(cx, enclosingScope);
if (!scope) {
scope = &cx->global()->emptyGlobalScope();
}
LifoAllocScope allocScope(&cx->tempLifoAlloc());
CompilationInfo compilationInfo(cx, allocScope, options, enclosingScope);
if (!compilationInfo.initForStandaloneFunction(cx, scope)) {
return nullptr;
}
StandaloneFunctionCompiler<char16_t> compiler(srcBuf);
if (!compiler.createSourceAndParser(allocScope, compilationInfo)) {
return nullptr;
}
FunctionNode* parsedFunction = compiler.parse(
compilationInfo, syntaxKind, generatorKind, asyncKind, parameterListEnd);
if (!parsedFunction) {
return nullptr;
}
RootedFunction fun(cx, compiler.compile(compilationInfo, parsedFunction));
if (!fun) {
return nullptr;
}
// Note: If AsmJS successfully compiles, the into.script will still be
// nullptr. In this case we have compiled to a native function instead of an
// interpreted script.
if (compilationInfo.script) {
if (parameterListEnd) {
compilationInfo.sourceObject->source()->setParameterListEnd(
*parameterListEnd);
}
tellDebuggerAboutCompiledScript(cx, options.hideScriptFromDebugger,
compilationInfo.script);
}
assertException.reset();
return fun;
}
JSFunction* frontend::CompileStandaloneFunction(
JSContext* cx, const JS::ReadOnlyCompileOptions& options,
JS::SourceText<char16_t>& srcBuf, const Maybe<uint32_t>& parameterListEnd,
FunctionSyntaxKind syntaxKind, HandleScope enclosingScope /* = nullptr */) {
return CompileStandaloneFunction(cx, options, srcBuf, parameterListEnd,
syntaxKind, GeneratorKind::NotGenerator,
FunctionAsyncKind::SyncFunction,
enclosingScope);
}
JSFunction* frontend::CompileStandaloneGenerator(
JSContext* cx, const JS::ReadOnlyCompileOptions& options,
JS::SourceText<char16_t>& srcBuf, const Maybe<uint32_t>& parameterListEnd,
FunctionSyntaxKind syntaxKind) {
return CompileStandaloneFunction(cx, options, srcBuf, parameterListEnd,
syntaxKind, GeneratorKind::Generator,
FunctionAsyncKind::SyncFunction);
}
JSFunction* frontend::CompileStandaloneAsyncFunction(
JSContext* cx, const ReadOnlyCompileOptions& options,
JS::SourceText<char16_t>& srcBuf, const Maybe<uint32_t>& parameterListEnd,
FunctionSyntaxKind syntaxKind) {
return CompileStandaloneFunction(cx, options, srcBuf, parameterListEnd,
syntaxKind, GeneratorKind::NotGenerator,
FunctionAsyncKind::AsyncFunction);
}
JSFunction* frontend::CompileStandaloneAsyncGenerator(
JSContext* cx, const ReadOnlyCompileOptions& options,
JS::SourceText<char16_t>& srcBuf, const Maybe<uint32_t>& parameterListEnd,
FunctionSyntaxKind syntaxKind) {
return CompileStandaloneFunction(cx, options, srcBuf, parameterListEnd,
syntaxKind, GeneratorKind::Generator,
FunctionAsyncKind::AsyncFunction);
}
bool frontend::CompilationInfo::init(JSContext* cx) {
sourceObject = CreateScriptSourceObject(cx, options);
return !!sourceObject;
}