-
Notifications
You must be signed in to change notification settings - Fork 316
/
Copy pathCompiler.swift
1233 lines (1084 loc) · 56.9 KB
/
Compiler.swift
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
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Compiles a JavaScript AST into a FuzzIL program.
public class JavaScriptCompiler {
public typealias AST = Compiler_Protobuf_AST
typealias StatementNode = Compiler_Protobuf_Statement
typealias ExpressionNode = Compiler_Protobuf_Expression
// Simple error enum for errors that are displayed to the user.
public enum CompilerError: Error {
case invalidASTError(String)
case invalidNodeError(String)
case unsupportedFeatureError(String)
}
public init() {}
/// The compiled code.
private var code = Code()
/// The environment is used to determine if an identifier identifies a builtin object.
/// TODO we should probably use the correct target environment, with any additional builtins etc. here. But for now, we just manually add `gc` since that's relatively common.
private var environment = JavaScriptEnvironment(additionalBuiltins: ["gc": .function()])
/// Contains the mapping from JavaScript variables to FuzzIL variables in every active scope.
private var scopes = Stack<[String: Variable]>()
/// The next free FuzzIL variable.
private var nextVariable = 0
/// Context analyzer to track the context of the code being compiled. Used for example to distinguish switch and loop breaks.
private var contextAnalyzer = ContextAnalyzer()
public func compile(_ ast: AST) throws -> Program {
reset()
try enterNewScope {
for statement in ast.statements {
try compileStatement(statement)
}
}
try code.check()
return Program(code: code)
}
/// Allocates the next free variable.
private func nextFreeVariable() -> Variable {
let v = Variable(number: nextVariable)
nextVariable += 1
return v
}
private func compileStatement(_ node: StatementNode) throws {
guard let stmt = node.statement else {
throw CompilerError.invalidASTError("missing concrete statement in statement node")
}
switch stmt {
case .emptyStatement:
break
case .blockStatement(let blockStatement):
emit(BeginBlockStatement())
try enterNewScope {
for statement in blockStatement.body {
try compileStatement(statement)
}
}
emit(EndBlockStatement())
case .variableDeclaration(let variableDeclaration):
for decl in variableDeclaration.declarations {
let initialValue: Variable
if decl.hasValue {
initialValue = try compileExpression(decl.value)
} else {
// TODO(saelo): consider caching the `undefined` value for future uses
initialValue = emit(LoadUndefined()).output
}
let declarationMode: NamedVariableDeclarationMode
switch variableDeclaration.kind {
case .var:
declarationMode = .var
case .let:
declarationMode = .let
case .const:
declarationMode = .const
case .UNRECOGNIZED(let type):
throw CompilerError.invalidNodeError("invalid variable declaration type \(type)")
}
let v = emit(CreateNamedVariable(decl.name, declarationMode: declarationMode), withInputs: [initialValue]).output
// Variables declared with .var are allowed to overwrite each other.
assert(!currentScope.keys.contains(decl.name) || declarationMode == .var)
mapOrRemap(decl.name, to: v)
}
case .functionDeclaration(let functionDeclaration):
let parameters = convertParameters(functionDeclaration.parameters)
let functionBegin, functionEnd: Operation
switch functionDeclaration.type {
case .plain:
functionBegin = BeginPlainFunction(parameters: parameters, isStrict: false)
functionEnd = EndPlainFunction()
case .generator:
functionBegin = BeginGeneratorFunction(parameters: parameters, isStrict: false)
functionEnd = EndGeneratorFunction()
case .async:
functionBegin = BeginAsyncFunction(parameters: parameters, isStrict: false)
functionEnd = EndAsyncFunction()
case .asyncGenerator:
functionBegin = BeginAsyncGeneratorFunction(parameters: parameters, isStrict: false)
functionEnd = EndAsyncGeneratorFunction()
case .UNRECOGNIZED(let type):
throw CompilerError.invalidNodeError("invalid function declaration type \(type)")
}
let instr = emit(functionBegin)
// The function may have been accessed before it was defined due to function hoisting, so
// here we may overwrite an existing variable mapping.
mapOrRemap(functionDeclaration.name, to: instr.output)
try enterNewScope {
mapParameters(functionDeclaration.parameters, to: instr.innerOutputs)
for statement in functionDeclaration.body {
try compileStatement(statement)
}
}
emit(functionEnd)
case .classDeclaration(let classDeclaration):
// The expressions for property values and computed properties need to be emitted before the class declaration is opened.
var propertyValues = [Variable]()
var computedPropertyKeys = [Variable]()
for field in classDeclaration.fields {
guard let field = field.field else {
throw CompilerError.invalidNodeError("missing concrete field in class declaration")
}
if case .property(let property) = field {
if property.hasValue {
propertyValues.append(try compileExpression(property.value))
}
if case .expression(let key) = property.key {
computedPropertyKeys.append(try compileExpression(key))
}
}
}
// Reverse the arrays since we'll remove the elements in FIFO order.
propertyValues.reverse()
computedPropertyKeys.reverse()
let classDecl: Instruction
if classDeclaration.hasSuperClass {
let superClass = try compileExpression(classDeclaration.superClass)
classDecl = emit(BeginClassDefinition(hasSuperclass: true), withInputs: [superClass])
} else {
classDecl = emit(BeginClassDefinition(hasSuperclass: false))
}
map(classDeclaration.name, to: classDecl.output)
for field in classDeclaration.fields {
switch field.field! {
case .property(let property):
guard let key = property.key else {
throw CompilerError.invalidNodeError("Missing key in class property")
}
let op: Operation
var inputs = [Variable]()
switch key {
case .name(let name):
if property.isStatic {
op = ClassAddStaticProperty(propertyName: name, hasValue: property.hasValue)
} else {
op = ClassAddInstanceProperty(propertyName: name, hasValue: property.hasValue)
}
case .index(let index):
if property.isStatic {
op = ClassAddStaticElement(index: index, hasValue: property.hasValue)
} else {
op = ClassAddInstanceElement(index: index, hasValue: property.hasValue)
}
case .expression:
inputs.append(computedPropertyKeys.removeLast())
if property.isStatic {
op = ClassAddStaticComputedProperty(hasValue: property.hasValue)
} else {
op = ClassAddInstanceComputedProperty(hasValue: property.hasValue)
}
}
if property.hasValue {
inputs.append(propertyValues.removeLast())
}
emit(op, withInputs: inputs)
case .ctor(let constructor):
let parameters = convertParameters(constructor.parameters)
let head = emit(BeginClassConstructor(parameters: parameters))
try enterNewScope {
var parameters = head.innerOutputs
map("this", to: parameters.removeFirst())
mapParameters(constructor.parameters, to: parameters)
for statement in constructor.body {
try compileStatement(statement)
}
}
emit(EndClassConstructor())
case .method(let method):
let parameters = convertParameters(method.parameters)
let head: Instruction
if method.isStatic {
head = emit(BeginClassStaticMethod(methodName: method.name, parameters: parameters))
} else {
head = emit(BeginClassInstanceMethod(methodName: method.name, parameters: parameters))
}
try enterNewScope {
var parameters = head.innerOutputs
map("this", to: parameters.removeFirst())
mapParameters(method.parameters, to: parameters)
for statement in method.body {
try compileStatement(statement)
}
}
if method.isStatic {
emit(EndClassStaticMethod())
} else {
emit(EndClassInstanceMethod())
}
case .getter(let getter):
let head: Instruction
if getter.isStatic {
head = emit(BeginClassStaticGetter(propertyName: getter.name))
} else {
head = emit(BeginClassInstanceGetter(propertyName: getter.name))
}
try enterNewScope {
map("this", to: head.innerOutput)
for statement in getter.body {
try compileStatement(statement)
}
}
if getter.isStatic {
emit(EndClassStaticGetter())
} else {
emit(EndClassInstanceGetter())
}
case .setter(let setter):
let head: Instruction
if setter.isStatic {
head = emit(BeginClassStaticSetter(propertyName: setter.name))
} else {
head = emit(BeginClassInstanceSetter(propertyName: setter.name))
}
try enterNewScope {
var parameters = head.innerOutputs
map("this", to: parameters.removeFirst())
mapParameters([setter.parameter], to: parameters)
for statement in setter.body {
try compileStatement(statement)
}
}
if setter.isStatic {
emit(EndClassStaticSetter())
} else {
emit(EndClassInstanceSetter())
}
case .staticInitializer(let staticInitializer):
let head = emit(BeginClassStaticInitializer())
try enterNewScope {
map("this", to: head.innerOutput)
for statement in staticInitializer.body {
try compileStatement(statement)
}
}
emit(EndClassStaticInitializer())
}
}
emit(EndClassDefinition())
case .returnStatement(let returnStatement):
if returnStatement.hasArgument {
let value = try compileExpression(returnStatement.argument)
emit(Return(hasReturnValue: true), withInputs: [value])
} else {
emit(Return(hasReturnValue: false))
}
case .expressionStatement(let expressionStatement):
try compileExpression(expressionStatement.expression)
case .ifStatement(let ifStatement):
let test = try compileExpression(ifStatement.test)
emit(BeginIf(inverted: false), withInputs: [test])
try enterNewScope {
try compileBody(ifStatement.ifBody)
}
if ifStatement.hasElseBody {
emit(BeginElse())
try enterNewScope {
try compileBody(ifStatement.elseBody)
}
}
emit(EndIf())
case .whileLoop(let whileLoop):
emit(BeginWhileLoopHeader())
try enterNewScope {
let cond = try compileExpression(whileLoop.test)
emit(BeginWhileLoopBody(), withInputs: [cond])
}
try enterNewScope {
try compileBody(whileLoop.body)
}
emit(EndWhileLoop())
case .doWhileLoop(let doWhileLoop):
emit(BeginDoWhileLoopBody())
try enterNewScope {
try compileBody(doWhileLoop.body)
}
emit(BeginDoWhileLoopHeader())
try enterNewScope {
let cond = try compileExpression(doWhileLoop.test)
emit(EndDoWhileLoop(), withInputs: [cond])
}
case .forLoop(let forLoop):
var loopVariables = [String]()
// Process initializer.
var initialLoopVariableValues = [Variable]()
emit(BeginForLoopInitializer())
try enterNewScope {
if let initializer = forLoop.initializer {
switch initializer {
case .declaration(let declaration):
for declarator in declaration.declarations {
loopVariables.append(declarator.name)
initialLoopVariableValues.append(try compileExpression(declarator.value))
}
case .expression(let expression):
try compileExpression(expression)
}
}
}
// Process condition.
var outputs = emit(BeginForLoopCondition(numLoopVariables: loopVariables.count), withInputs: initialLoopVariableValues).innerOutputs
var cond: Variable? = nil
try enterNewScope {
zip(loopVariables, outputs).forEach({ map($0, to: $1 )})
if forLoop.hasCondition {
cond = try compileExpression(forLoop.condition)
} else {
cond = emit(LoadBoolean(value: true)).output
}
}
// Process afterthought.
outputs = emit(BeginForLoopAfterthought(numLoopVariables: loopVariables.count), withInputs: [cond!]).innerOutputs
try enterNewScope {
zip(loopVariables, outputs).forEach({ map($0, to: $1 )})
if forLoop.hasAfterthought {
try compileExpression(forLoop.afterthought)
}
}
// Process body
outputs = emit(BeginForLoopBody(numLoopVariables: loopVariables.count)).innerOutputs
try enterNewScope {
zip(loopVariables, outputs).forEach({ map($0, to: $1 )})
try compileBody(forLoop.body)
}
emit(EndForLoop())
case .forInLoop(let forInLoop):
let initializer = forInLoop.left;
guard !initializer.hasValue else {
throw CompilerError.invalidNodeError("Expected no initial value for the variable declared in a for-in loop")
}
let obj = try compileExpression(forInLoop.right)
let loopVar = emit(BeginForInLoop(), withInputs: [obj]).innerOutput
try enterNewScope {
map(initializer.name, to: loopVar)
try compileBody(forInLoop.body)
}
emit(EndForInLoop())
case .forOfLoop(let forOfLoop):
let initializer = forOfLoop.left;
guard !initializer.hasValue else {
throw CompilerError.invalidNodeError("Expected no initial value for the variable declared in a for-of loop")
}
let obj = try compileExpression(forOfLoop.right)
let loopVar = emit(BeginForOfLoop(), withInputs: [obj]).innerOutput
try enterNewScope {
map(initializer.name, to: loopVar)
try compileBody(forOfLoop.body)
}
emit(EndForOfLoop())
case .breakStatement:
// If we're in both .loop and .switch context, then the loop must be the most recent context
// (switch blocks don't propagate an outer .loop context) so we just need to check for .loop here
if contextAnalyzer.context.contains(.loop){
emit(LoopBreak())
} else if contextAnalyzer.context.contains(.switchCase) {
emit(SwitchBreak())
} else {
throw CompilerError.invalidNodeError("break statement outside of loop or switch")
}
case .continueStatement:
emit(LoopContinue())
case .tryStatement(let tryStatement):
emit(BeginTry())
try enterNewScope {
for statement in tryStatement.body {
try compileStatement(statement)
}
}
if tryStatement.hasCatch {
try enterNewScope {
let beginCatch = emit(BeginCatch())
if tryStatement.catch.hasParameter {
map(tryStatement.catch.parameter.name, to: beginCatch.innerOutput)
}
for statement in tryStatement.catch.body {
try compileStatement(statement)
}
}
}
if tryStatement.hasFinally {
try enterNewScope {
emit(BeginFinally())
for statement in tryStatement.finally.body {
try compileStatement(statement)
}
}
}
emit(EndTryCatchFinally())
case .throwStatement(let throwStatement):
let value = try compileExpression(throwStatement.argument)
emit(ThrowException(), withInputs: [value])
case .withStatement(let withStatement):
let object = try compileExpression(withStatement.object)
emit(BeginWith(), withInputs: [object])
try enterNewScope {
try compileBody(withStatement.body)
}
emit(EndWith())
case .switchStatement(let switchStatement):
// TODO Replace the precomputation of tests with compilation of the test expressions in the cases.
// To do this, we would need to redesign Switch statements in FuzzIL to (for example) have a BeginSwitchCaseHead, BeginSwitchCaseBody, and EndSwitchCase.
// Then the expression would go inside the header.
var precomputedTests = [Variable]()
for caseStatement in switchStatement.cases {
if caseStatement.hasTest {
let test = try compileExpression(caseStatement.test)
precomputedTests.append(test)
}
}
let discriminant = try compileExpression(switchStatement.discriminant)
emit(BeginSwitch(), withInputs: [discriminant])
for caseStatement in switchStatement.cases {
if caseStatement.hasTest {
emit(BeginSwitchCase(), withInputs: [precomputedTests.removeFirst()])
} else {
emit(BeginSwitchDefaultCase())
}
try enterNewScope {
for statement in caseStatement.consequent {
try compileStatement(statement)
}
}
// We could also do an optimization here where we check if the last statement in the case is a break, and if so, we drop the last instruction
// and set the fallsThrough flag to false.
emit(EndSwitchCase(fallsThrough: true))
}
emit(EndSwitch())
}
}
// This is essentially the same as compileStatement except that it skips a top-level BlockStatement:
// For example, the body of a loop is a single statement. If the body consists of multiple statements
// then the "top-level" statement is a BlockStatement. When compiling such code to FuzzIL, that
// top-level BlockStatement should be skipped as it would otherwise turn into a separate Begin/EndBlock.
// This does not modify the current scope, the caller is expected to do that.
private func compileBody(_ statement: StatementNode) throws {
if case .blockStatement(let blockStatement) = statement.statement {
for statement in blockStatement.body {
try compileStatement(statement)
}
} else {
try compileStatement(statement)
}
}
@discardableResult
private func compileExpression(_ node: ExpressionNode) throws -> Variable {
guard let expr = node.expression else {
throw CompilerError.invalidASTError("missing concrete expression in expression node")
}
switch expr {
case .ternaryExpression(let ternaryExpression):
let condition = try compileExpression(ternaryExpression.condition)
let consequent = try compileExpression(ternaryExpression.consequent)
let alternate = try compileExpression(ternaryExpression.alternate)
return emit(TernaryOperation(), withInputs: [condition, consequent, alternate]).output
case .identifier(let identifier):
// Identifiers can generally turn into one of three things:
// 1. A FuzzIL variable that has previously been associated with the identifier
// 2. A LoadUndefined or LoadArguments operations if the identifier is "undefined" or "arguments" respectively
// 3. A CreateNamedVariable operation in all other cases (typically global or hoisted variables, but could also be properties in a with statement)
// We currently fall-back to case 3 if none of the other works. However, this isn't quite correct as it would incorrectly deal with e.g.
//
// let v = 42;
// function foo() {
// v = 5;
// var v = 3;
// }
// foo()
//
// As the `v = 5` would end up changing the outer variable.
// TODO To deal with this correctly, we'd have to walk over the AST twice.
// Case 1
if let v = lookupIdentifier(identifier.name) {
return v
}
// Case 2
assert(identifier.name != "this") // This is handled via ThisExpression
if identifier.name == "undefined" {
return emit(LoadUndefined()).output
} else if identifier.name == "arguments" {
return emit(LoadArguments()).output
}
// Case 3
let v = emit(CreateNamedVariable(identifier.name, declarationMode: .none)).output
// Cache the variable in case it is reused again to avoid emitting multiple
// CreateNamedVariable operations for the same variable.
map(identifier.name, to: v)
return v
case .numberLiteral(let literal):
if let intValue = Int64(exactly: literal.value) {
return emit(LoadInteger(value: intValue)).output
} else {
return emit(LoadFloat(value: literal.value)).output
}
case .bigIntLiteral(let literal):
if let intValue = Int64(literal.value) {
return emit(LoadBigInt(value: intValue)).output
} else {
// TODO should LoadBigInt support larger integer values (represented as string)?
let stringValue = emit(LoadString(value: literal.value)).output
let BigInt = emit(CreateNamedVariable("BigInt", declarationMode: .none)).output
return emit(CallFunction(numArguments: 1, isGuarded: false), withInputs: [BigInt, stringValue]).output
}
case .stringLiteral(let literal):
let value = literal.value.replacingOccurrences(of: "\n", with: "\\n")
return emit(LoadString(value: value)).output
case .templateLiteral(let templateLiteral):
let interpolatedValues = try templateLiteral.expressions.map(compileExpression)
let parts = templateLiteral.parts.map({ $0.replacingOccurrences(of: "\n", with: "\\n") })
return emit(CreateTemplateString(parts: parts), withInputs: interpolatedValues).output
case .regExpLiteral(let literal):
guard let flags = RegExpFlags.fromString(literal.flags) else {
throw CompilerError.invalidNodeError("invalid RegExp flags: \(literal.flags)")
}
return emit(LoadRegExp(pattern: literal.pattern, flags: flags)).output
case .booleanLiteral(let literal):
return emit(LoadBoolean(value: literal.value)).output
case .nullLiteral:
return emit(LoadNull()).output
case .thisExpression:
// Check if `this` is currently mapped to a FuzzIL variable (e.g. if we're inside an object- or class method).
if let v = lookupIdentifier("this") {
return v
}
// Otherwise, emit a LoadThis.
return emit(LoadThis()).output
case .assignmentExpression(let assignmentExpression):
guard let lhs = assignmentExpression.lhs.expression else {
throw CompilerError.invalidNodeError("Missing lhs in assignment expression")
}
let rhs = try compileExpression(assignmentExpression.rhs)
let assignmentOperator: BinaryOperator?
switch assignmentExpression.operator {
case "=":
assignmentOperator = nil
default:
// It's something like "+=", "-=", etc.
let binaryOperator = String(assignmentExpression.operator.dropLast())
guard let op = BinaryOperator(rawValue: binaryOperator) else {
throw CompilerError.invalidNodeError("Unknown assignment operator \(assignmentExpression.operator)")
}
assignmentOperator = op
}
switch lhs {
case .memberExpression(let memberExpression):
// Compile to a Set- or Update{Property/Element/ComputedProperty} operation
let object = try compileExpression(memberExpression.object)
guard let property = memberExpression.property else { throw CompilerError.invalidNodeError("missing property in member expression") }
switch property {
case .name(let name):
if let op = assignmentOperator {
emit(UpdateProperty(propertyName: name, operator: op), withInputs: [object, rhs])
} else {
emit(SetProperty(propertyName: name), withInputs: [object, rhs])
}
case .expression(let expr):
if case .numberLiteral(let literal) = expr.expression, let index = Int64(exactly: literal.value) {
if let op = assignmentOperator {
emit(UpdateElement(index: index, operator: op), withInputs: [object, rhs])
} else {
emit(SetElement(index: index), withInputs: [object, rhs])
}
} else {
let property = try compileExpression(expr)
if let op = assignmentOperator {
emit(UpdateComputedProperty(operator: op), withInputs: [object, property, rhs])
} else {
emit(SetComputedProperty(), withInputs: [object, property, rhs])
}
}
}
case .superMemberExpression(let superMemberExpression):
guard superMemberExpression.isOptional == false else {
throw CompilerError.unsupportedFeatureError("Optional chaining is not supported in super member expressions")
}
guard let property = superMemberExpression.property else {
throw CompilerError.invalidNodeError("Missing property in super member expression")
}
switch property {
case .name(let name):
if let op = assignmentOperator {
// Example: super.foo += 1
emit(UpdateSuperProperty(propertyName: name, operator: op), withInputs: [rhs])
} else {
// Example: super.foo = 1
emit(SetSuperProperty(propertyName: name), withInputs: [rhs])
}
case .expression(let expr):
let property = try compileExpression(expr)
// Example: super[expr] = 1
emit(SetComputedSuperProperty(), withInputs: [property, rhs])
}
case .identifier(let identifier):
// Try to lookup the variable belonging to the identifier. If there is none, we're (probably) dealing with
// an access to a global variable/builtin or a hoisted variable access. In the case, create a named variable.
let lhs = lookupIdentifier(identifier.name) ?? emit(CreateNamedVariable(identifier.name, declarationMode: .none)).output
// Compile to a Reassign or Update operation
switch assignmentExpression.operator {
case "=":
// TODO(saelo): if we're assigning to a named variable, we could also generate a declaration
// of a global variable here instead. Probably it doeesn't matter in practice though.
emit(Reassign(), withInputs: [lhs, rhs])
default:
// It's something like "+=", "-=", etc.
let binaryOperator = String(assignmentExpression.operator.dropLast())
guard let op = BinaryOperator(rawValue: binaryOperator) else {
throw CompilerError.invalidNodeError("Unknown assignment operator \(assignmentExpression.operator)")
}
emit(Update(op), withInputs: [lhs, rhs])
}
default:
throw CompilerError.unsupportedFeatureError("Compiler only supports assignments to object members or identifiers")
}
return rhs
case .objectExpression(let objectExpression):
// The expressions for property values and computed properties need to be emitted before the object literal is opened.
var propertyValues = [Variable]()
var computedPropertyKeys = [Variable]()
for field in objectExpression.fields {
guard let field = field.field else {
throw CompilerError.invalidNodeError("missing concrete field in object expression")
}
if case .property(let property) = field {
propertyValues.append(try compileExpression(property.value))
if case .expression(let expression) = property.key {
computedPropertyKeys.append(try compileExpression(expression))
}
} else if case .method(let method) = field {
if case .expression(let expression) = method.key {
computedPropertyKeys.append(try compileExpression(expression))
}
}
}
// Reverse the arrays since we'll remove the elements in FIFO order.
propertyValues.reverse()
computedPropertyKeys.reverse()
// Now build the object literal.
emit(BeginObjectLiteral())
for field in objectExpression.fields {
switch field.field! {
case .property(let property):
guard let key = property.key else {
throw CompilerError.invalidNodeError("missing key in object expression field")
}
let inputs = [propertyValues.removeLast()]
switch key {
case .name(let name):
emit(ObjectLiteralAddProperty(propertyName: name), withInputs: inputs)
case .index(let index):
emit(ObjectLiteralAddElement(index: index), withInputs: inputs)
case .expression:
emit(ObjectLiteralAddComputedProperty(), withInputs: [computedPropertyKeys.removeLast()] + inputs)
}
case .method(let method):
let parameters = convertParameters(method.parameters)
let instr: Instruction
if case .name(let name) = method.key {
instr = emit(BeginObjectLiteralMethod(methodName: name, parameters: parameters))
} else {
instr = emit(BeginObjectLiteralComputedMethod(parameters: parameters), withInputs: [computedPropertyKeys.removeLast()])
}
try enterNewScope {
var parameters = instr.innerOutputs
map("this", to: parameters.removeFirst())
mapParameters(method.parameters, to: parameters)
for statement in method.body {
try compileStatement(statement)
}
}
if case .name = method.key {
emit(EndObjectLiteralMethod())
} else {
emit(EndObjectLiteralComputedMethod())
}
case .getter(let getter):
guard case .name(let name) = getter.key else {
fatalError("Computed getters are not yet supported")
}
let instr = emit(BeginObjectLiteralGetter(propertyName: name))
try enterNewScope {
map("this", to: instr.innerOutput)
for statement in getter.body {
try compileStatement(statement)
}
}
emit(EndObjectLiteralGetter())
case .setter(let setter):
guard case .name(let name) = setter.key else {
fatalError("Computed setters are not yet supported")
}
let instr = emit(BeginObjectLiteralSetter(propertyName: name))
try enterNewScope {
var parameters = instr.innerOutputs
map("this", to: parameters.removeFirst())
mapParameters([setter.parameter], to: parameters)
for statement in setter.body {
try compileStatement(statement)
}
}
emit(EndObjectLiteralSetter())
}
}
return emit(EndObjectLiteral()).output
case .arrayExpression(let arrayExpression):
var elements = [Variable]()
var undefined: Variable? = nil
var spreads = [Bool]()
for elem in arrayExpression.elements {
if elem.expression == nil {
if undefined == nil {
undefined = emit(LoadUndefined()).output
}
elements.append(undefined!)
spreads.append(false)
} else {
if case .spreadElement(let spreadElement) = elem.expression {
elements.append(try compileExpression(spreadElement.argument))
spreads.append(true)
} else {
elements.append(try compileExpression(elem))
spreads.append(false)
}
}
}
if spreads.contains(true) {
return emit(CreateArrayWithSpread(spreads: spreads), withInputs: elements).output
} else {
return emit(CreateArray(numInitialValues: elements.count), withInputs: elements).output
}
case .functionExpression(let functionExpression):
let parameters = convertParameters(functionExpression.parameters)
let functionBegin, functionEnd: Operation
switch functionExpression.type {
case .plain:
functionBegin = BeginPlainFunction(parameters: parameters, isStrict: false)
functionEnd = EndPlainFunction()
case .generator:
functionBegin = BeginGeneratorFunction(parameters: parameters, isStrict: false)
functionEnd = EndGeneratorFunction()
case .async:
functionBegin = BeginAsyncFunction(parameters: parameters, isStrict: false)
functionEnd = EndAsyncFunction()
case .asyncGenerator:
functionBegin = BeginAsyncGeneratorFunction(parameters: parameters, isStrict: false)
functionEnd = EndAsyncGeneratorFunction()
case .UNRECOGNIZED(let type):
throw CompilerError.invalidNodeError("invalid function declaration type \(type)")
}
let instr = emit(functionBegin)
try enterNewScope {
mapParameters(functionExpression.parameters, to: instr.innerOutputs)
for statement in functionExpression.body {
try compileStatement(statement)
}
}
emit(functionEnd)
return instr.output
case .arrowFunctionExpression(let arrowFunction):
let parameters = convertParameters(arrowFunction.parameters)
let functionBegin, functionEnd: Operation
switch arrowFunction.type {
case .plain:
functionBegin = BeginArrowFunction(parameters: parameters, isStrict: false)
functionEnd = EndArrowFunction()
case .async:
functionBegin = BeginAsyncArrowFunction(parameters: parameters, isStrict: false)
functionEnd = EndAsyncArrowFunction()
default:
throw CompilerError.invalidNodeError("invalid arrow function type \(arrowFunction.type)")
}
let instr = emit(functionBegin)
try enterNewScope {
mapParameters(arrowFunction.parameters, to: instr.innerOutputs)
guard let body = arrowFunction.body else { throw CompilerError.invalidNodeError("missing body in arrow function") }
switch body {
case .block(let block):
try compileStatement(block)
case .expression(let expr):
let result = try compileExpression(expr)
emit(Return(hasReturnValue: true), withInputs: [result])
}
}
emit(functionEnd)
return instr.output
case .callExpression(let callExpression):
let (arguments, spreads) = try compileCallArguments(callExpression.arguments)
let isSpreading = spreads.contains(true)
// See if this is a function or a method call
if case .memberExpression(let memberExpression) = callExpression.callee.expression {
// obj.foo(...) or obj[expr](...)
let object = try compileExpression(memberExpression.object)
guard let property = memberExpression.property else { throw CompilerError.invalidNodeError("missing property in member expression in call expression") }
switch property {
case .name(let name):
if isSpreading {
return emit(CallMethodWithSpread(methodName: name, numArguments: arguments.count, spreads: spreads, isGuarded: callExpression.isOptional), withInputs: [object] + arguments).output
} else {
return emit(CallMethod(methodName: name, numArguments: arguments.count, isGuarded: callExpression.isOptional), withInputs: [object] + arguments).output
}
case .expression(let expr):
let method = try compileExpression(expr)
if isSpreading {
return emit(CallComputedMethodWithSpread(numArguments: arguments.count, spreads: spreads, isGuarded: callExpression.isOptional), withInputs: [object, method] + arguments).output
} else {
return emit(CallComputedMethod(numArguments: arguments.count, isGuarded: callExpression.isOptional), withInputs: [object, method] + arguments).output
}
}
} else if case .superMemberExpression(let superMemberExpression) = callExpression.callee.expression {
// super.foo(...)
guard !isSpreading else {
throw CompilerError.unsupportedFeatureError("Spread calls with super are not supported")
}
guard case .name(let methodName) = superMemberExpression.property else {
throw CompilerError.invalidNodeError("Super method calls must use a property name")
}
guard !callExpression.isOptional else {
throw CompilerError.unsupportedFeatureError("Optional chaining with super method calls is not supported")
}
return emit(CallSuperMethod(methodName: methodName, numArguments: arguments.count), withInputs: arguments).output
// Now check if it is a V8 intrinsic function
} else if case .v8IntrinsicIdentifier(let v8Intrinsic) = callExpression.callee.expression {
guard !isSpreading else { throw CompilerError.unsupportedFeatureError("Not currently supporting spread calls to V8 intrinsics") }
let argsString = Array(repeating: "%@", count: arguments.count).joined(separator: ", ")
return emit(Eval("%\(v8Intrinsic.name)(\(argsString))", numArguments: arguments.count, hasOutput: true), withInputs: arguments).output
// Otherwise it's a regular function call
} else {
guard !callExpression.isOptional else { throw CompilerError.unsupportedFeatureError("Not currently supporting optional chaining with function calls") }
let callee = try compileExpression(callExpression.callee)
if isSpreading {
return emit(CallFunctionWithSpread(numArguments: arguments.count, spreads: spreads, isGuarded: false), withInputs: [callee] + arguments).output
} else {
return emit(CallFunction(numArguments: arguments.count, isGuarded: false), withInputs: [callee] + arguments).output
}
}
case .callSuperConstructor(let callSuperConstructor):
let (arguments, spreads) = try compileCallArguments(callSuperConstructor.arguments)
let isSpreading = spreads.contains(true)
if isSpreading {
throw CompilerError.unsupportedFeatureError("Spread arguments are not supported in super constructor calls")
}
guard !callSuperConstructor.isOptional else {
throw CompilerError.unsupportedFeatureError("Optional chaining is not supported in super constructor calls")
}
emit(CallSuperConstructor(numArguments: arguments.count), withInputs: arguments)
// In JS, the result of calling the super constructor is just |this|, but in FuzzIL the operation doesn't have an output (because |this| is always available anyway)
return lookupIdentifier("this")! // we can force unwrap because |this| always exists in the context where |super| exists
case .newExpression(let newExpression):
let callee = try compileExpression(newExpression.callee)
let (arguments, spreads) = try compileCallArguments(newExpression.arguments)
let isSpreading = spreads.contains(true)
if isSpreading {
return emit(ConstructWithSpread(numArguments: arguments.count, spreads: spreads, isGuarded: false), withInputs: [callee] + arguments).output
} else {