forked from nicklockwood/ShapeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterpreter.swift
More file actions
1373 lines (1341 loc) · 56.3 KB
/
Interpreter.swift
File metadata and controls
1373 lines (1341 loc) · 56.3 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
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
//
// Interpreter.swift
// ShapeScript
//
// Created by Nick Lockwood on 26/09/2018.
// Copyright © 2018 Nick Lockwood. All rights reserved.
//
import Euclid
import Foundation
// MARK: Public interface
public let version = "1.5.1"
public protocol EvaluationDelegate: AnyObject {
func resolveURL(for path: String) -> URL
func importGeometry(for url: URL) throws -> Geometry?
func debugLog(_ values: [AnyHashable])
}
public func evaluate(
_ program: Program,
delegate: EvaluationDelegate?,
cache: GeometryCache? = GeometryCache(),
isCancelled: @escaping () -> Bool = { false }
) throws -> Scene {
let context = EvaluationContext(
source: program.source,
delegate: delegate,
isCancelled: isCancelled
)
try program.evaluate(in: context)
return Scene(
background: context.background,
children: context.children.compactMap { $0.value as? Geometry },
cache: cache
)
}
public enum ImportError: Error, Equatable {
case lexerError(LexerError)
case parserError(ParserError)
case runtimeError(RuntimeError)
case unknownError
}
public extension ImportError {
init(_ error: Error) {
switch error {
case let error as LexerError: self = .lexerError(error)
case let error as ParserError: self = .parserError(error)
case let error as RuntimeError: self = .runtimeError(error)
default: self = .unknownError
}
}
var message: String {
switch self {
case let .lexerError(error): return error.message
case let .parserError(error): return error.message
case let .runtimeError(error): return error.message
case .unknownError: return "Unknown error"
}
}
var range: SourceRange {
switch self {
case let .lexerError(error): return error.range
case let .parserError(error): return error.range
case let .runtimeError(error): return error.range
case .unknownError: return "".startIndex ..< "".endIndex
}
}
var hint: String? {
switch self {
case let .lexerError(error): return error.hint
case let .parserError(error): return error.hint
case let .runtimeError(error): return error.hint
case .unknownError: return nil
}
}
}
public enum RuntimeErrorType: Error, Equatable {
case unknownSymbol(String, options: [String])
case unknownMember(String, of: String, options: [String])
case unknownFont(String, options: [String])
case typeMismatch(for: String, index: Int, expected: String, got: String)
case unexpectedArgument(for: String, max: Int)
case missingArgument(for: String, index: Int, type: String)
case unusedValue(type: String)
case assertionFailure(String)
case fileNotFound(for: String, at: URL?)
case fileAccessRestricted(for: String, at: URL)
case fileTypeMismatch(for: String, at: URL, expected: String?)
case fileParsingError(for: String, at: URL, message: String)
indirect case importError(ImportError, for: String, in: String)
}
public struct RuntimeError: Error, Equatable {
public let type: RuntimeErrorType
public let range: SourceRange
public init(_ type: RuntimeErrorType, at range: SourceRange) {
self.type = type
self.range = range
}
}
public extension RuntimeError {
var message: String {
switch type {
case let .unknownSymbol(name, _):
if Keyword(rawValue: name) == nil, Symbols.all[name] == nil {
return "Unknown symbol '\(name)'"
}
return "Unexpected symbol '\(name)'"
case let .unknownMember(name, type, _):
return "Unknown \(type) member property '\(name)'"
case let .unknownFont(name, _):
return name.isEmpty ? "Font name cannot be blank" : "Unknown font '\(name)'"
case .typeMismatch:
return "Type mismatch"
case .unexpectedArgument:
return "Unexpected argument"
case .missingArgument:
return "Missing argument"
case .unusedValue:
return "Unused value"
case .assertionFailure:
return "Assertion failure"
case let .fileNotFound(for: name, _):
guard !name.isEmpty else {
return "Empty file name"
}
return "File '\(name)' not found"
case let .fileAccessRestricted(for: name, _):
return "Unable to access file '\(name)'"
case let .fileParsingError(for: name, _, _),
let .fileTypeMismatch(for: name, _, _):
return "Unable to open file '\(name)'"
case let .importError(error, for: name, _):
if case let .runtimeError(error) = error, case .importError = error.type {
return error.message
}
return "Error in imported file '\(name)': \(error.message)"
}
}
var suggestion: String? {
switch type {
case let .unknownSymbol(name, options), let .unknownMember(name, _, options):
return Self.alternatives[name.lowercased()]?
.first(where: { options.contains($0) || Keyword(rawValue: $0) != nil })
?? name.bestMatches(in: options).first
case let .unknownFont(name, options):
return name.bestMatches(in: options).first
case .typeMismatch,
.unexpectedArgument,
.missingArgument,
.unusedValue,
.assertionFailure,
.fileNotFound,
.fileAccessRestricted,
.fileTypeMismatch,
.fileParsingError,
.importError:
return nil
}
}
var hint: String? {
func nth(_ index: Int) -> String {
switch index {
case 1 ..< String.ordinals.count:
return "\(String.ordinals[index]) "
default:
return ""
}
}
func formatMessage(_ message: String) -> String? {
guard let last = message.last else {
return nil
}
if ".?!".contains(last) {
return message
}
return "\(message)."
}
switch type {
case let .unknownSymbol(name, _):
var hint = ""
if let symbol = Symbols.all[name] {
hint = "The \(name) \(symbol.errorDescription) is not available in this context."
} else if Keyword(rawValue: name) != nil {
hint = "The \(name) command is not available in this context."
}
if let suggestion = suggestion {
hint += (hint.isEmpty ? "" : " ") + "Did you mean '\(suggestion)'?"
}
return hint
case .unknownMember:
return suggestion.map { "Did you mean '\($0)'?" }
case .unknownFont:
if let suggestion = suggestion {
return "Did you mean '\(suggestion)'?"
}
return ""
case let .typeMismatch(for: name, index: index, expected: type, got: got):
let got = got.contains(",") ? got : "a \(got)"
return "The \(nth(index))argument for \(name) should be a \(type), not \(got)."
case let .unexpectedArgument(for: name, max: max):
let name = name.isEmpty ? "Function" : "The \(name) function"
if max == 0 {
return "\(name) does not expect any arguments."
} else if max == 1 {
return "\(name) expects only a single argument."
} else {
return "\(name) expects a maximum of \(max) arguments."
}
case let .missingArgument(for: name, index: index, type: type):
var type = type
switch type {
case ValueType.pair.errorDescription:
type = ValueType.number.errorDescription
case ValueType.tuple.errorDescription:
type = ""
default:
break
}
type = type.isEmpty ? "" : " of type \(type)"
let name = name.isEmpty ? "Function" : "The \(name) function"
if index == 0 {
return "\(name) expects an argument\(type)."
} else {
return "\(name) expects a \(nth(index))argument\(type)."
}
case let .unusedValue(type: type):
return "A \(type) value was not expected in this context."
case let .assertionFailure(message):
return formatMessage(message)
case let .fileNotFound(for: name, at: url):
guard let url = url else {
return nil
}
if name == url.path {
return "Check that the file exists and is located here."
}
return "ShapeScript expected to find the file at '\(url.path)'."
+ " Check that it exists and is located here."
case let .fileAccessRestricted(for: _, at: url):
return "ShapeScript cannot read the file due to \(Self.osName) security restrictions."
+ " Please open the directory at '\(url.path)' to grant access."
case let .fileParsingError(for: _, at: _, message: message):
return formatMessage(message)
case let .fileTypeMismatch(for: _, at: url, expected: type):
guard let type = type else {
return "The type of file at '\(url.path)' is not supported."
}
return "The file at '\(url.path)' is not a \(type) file."
case let .importError(error, for: _, in: _):
return error.hint
}
}
static func wrap<T>(_ fn: @autoclosure () throws -> T, at range: SourceRange) throws -> T {
do {
return try fn()
} catch let error as RuntimeErrorType {
throw RuntimeError(error, at: range)
}
}
}
// MARK: Implementation
private struct EvaluationCancelled: Error {}
private extension RuntimeError {
static let alternatives = [
"box": ["cube"],
"rect": ["square"],
"rectangle": ["square"],
"ellipse": ["circle"],
"elipse": ["circle"],
"squircle": ["roundrect"],
"rotate": ["orientation"],
"rotation": ["orientation"],
"orientation": ["rotate"],
"translate": ["position"],
"translation": ["position"],
"position": ["translate"],
"scale": ["size"],
"size": ["scale"],
"width": ["size", "x"],
"height": ["size", "y"],
"depth": ["size", "z"],
"length": ["size"],
"radius": ["size"],
"x": ["width", "position"],
"y": ["height", "position"],
"z": ["depth", "position"],
"option": ["define"],
"subtract": ["difference"],
"subtraction": ["difference"],
]
static let osName: String = {
#if os(macOS) || targetEnvironment(macCatalyst)
return "macOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(iOS)
return "iOS"
#else
return "system"
#endif
}()
}
private extension RuntimeErrorType {
static func typeMismatch(
for symbol: String,
index: Int,
expected types: [String],
got: String
) -> RuntimeErrorType {
var types = Set(types).sorted()
if let index = types.firstIndex(of: "block") {
types.append(types.remove(at: index))
}
let expected: String
switch types.count {
case 1:
expected = types[0]
case 2:
expected = "\(types[0]) or \(types[1])"
default:
expected = "\(types.dropLast().joined(separator: ", ")), or \(types.last!)"
}
return .typeMismatch(for: symbol, index: index, expected: expected, got: got)
}
}
extension Program {
func evaluate(in context: EvaluationContext) throws {
let oldSource = context.source
context.source = source
defer { context.source = oldSource }
do {
try statements.forEach { try $0.evaluate(in: context) }
} catch is EvaluationCancelled {}
}
}
private func evaluateParameters(
_ parameters: [Expression],
in context: EvaluationContext
) throws -> [Value] {
var values = [Value]()
loop: for (i, param) in parameters.enumerated() {
guard i < parameters.count - 1, case let .identifier(name) = param.type,
let symbol = context.symbol(for: name)
else {
try values.append(param.evaluate(in: context))
continue
}
switch symbol {
case let .function(parameterType, fn) where parameterType != .void:
let identifier = Identifier(name: name, range: param.range)
let range = parameters[i + 1].range.lowerBound ..< parameters.last!.range.upperBound
let param = Expression(type: .tuple(Array(parameters[(i + 1)...])), range: range)
let arg = try evaluateParameter(param, as: parameterType, for: identifier, in: context)
try RuntimeError.wrap({
do {
try values.append(fn(arg, context))
} catch let RuntimeErrorType.unexpectedArgument(for: "", max: max) {
throw RuntimeErrorType.unexpectedArgument(for: name, max: max)
} catch let RuntimeErrorType.missingArgument(for: "", index: index, type: type) {
throw RuntimeErrorType.missingArgument(for: name, index: index, type: type)
}
}(), at: range)
break loop
case let .block(type, fn) where !type.childTypes.isEmpty:
let childContext = context.push(type)
let children = try evaluateParameters(Array(parameters[(i + 1)...]), in: context)
for (j, child) in children.enumerated() {
do {
try childContext.addValue(child)
} catch {
var types = type.childTypes.map { $0.errorDescription }
if j == 0 {
types.append("block")
}
throw RuntimeError(
.typeMismatch(
for: name,
index: j,
expected: types,
got: child.type.errorDescription
),
at: parameters[i + 1 + j].range
)
}
}
try RuntimeError.wrap(values.append(fn(childContext)), at: param.range)
break loop
case .command, .function, .block, .property, .constant:
try values.append(param.evaluate(in: context))
}
}
return values
}
// TODO: find a better way to encapsulate this
private func evaluateParameter(_ parameter: Expression?,
as type: ValueType,
for identifier: Identifier,
in context: EvaluationContext) throws -> Value
{
let (name, range) = (identifier.name, identifier.range)
guard let parameter = parameter else {
if type == .void {
return .void
}
throw RuntimeError(
.missingArgument(for: name, index: 0, type: type.errorDescription),
at: range.upperBound ..< range.upperBound
)
}
return try parameter.evaluate(as: type, for: identifier.name, in: context)
}
extension Definition {
func evaluate(in context: EvaluationContext) throws -> Symbol {
switch type {
case let .expression(expression):
let context = context.pushDefinition()
let value = try expression.evaluate(in: context)
switch value {
case .tuple:
return .constant(value)
default:
// Wrap all definitions as a single-value tuple
// so that ordinal access and looping will work
return .constant(.tuple([value]))
}
case let .function(names, block):
let declarationContext = context
return .function(names.isEmpty ? .void : .tuple) { value, context in
do {
let oldChildren = context.children
let oldChildTypes = context.childTypes
let oldSymbols = context.userSymbols
let oldSource = context.source
let oldBaseURL = context.baseURL
context.children = []
context.childTypes = ValueType.any
context.source = declarationContext.source
context.baseURL = declarationContext.baseURL
context.userSymbols = declarationContext.userSymbols
context.stackDepth += 1
defer {
context.children = oldChildren
context.childTypes = oldChildTypes
context.source = oldSource
context.baseURL = oldBaseURL
context.userSymbols = oldSymbols
context.stackDepth -= 1
}
if context.stackDepth > 25 {
throw RuntimeErrorType.assertionFailure("Too much recursion")
}
let values: [Value]
if case let .tuple(_values) = value {
values = _values
} else {
values = [value]
}
guard values.count == names.count else {
if values.count < names.count {
throw RuntimeErrorType
.missingArgument(for: "", index: values.count, type: "")
}
throw RuntimeErrorType
.unexpectedArgument(for: "", max: names.count)
}
for (identifier, value) in zip(names, values) {
context.define(identifier.name, as: .constant(value))
}
for statement in block.statements {
try statement.evaluate(in: context)
}
if context.children.count == 1 {
return context.children[0]
}
return .tuple(context.children)
} catch var error {
if let e = error as? RuntimeError,
case let .unknownSymbol(name, options: options) = e.type
{
// TODO: find a less hacky way to limit the scope of option keyword
error = RuntimeError(
.unknownSymbol(name, options: options + ["option"]),
at: e.range
)
}
if declarationContext.baseURL == context.baseURL {
throw error
}
throw RuntimeErrorType.importError(
ImportError(error),
for: declarationContext.baseURL?.lastPathComponent ?? "",
in: declarationContext.source
)
}
}
case let .block(block):
var options = Options()
do {
let context = context.push(.custom(.user, [:]))
context.random = RandomSequence(seed: context.random.seed)
for statement in block.statements {
switch statement.type {
case let .option(identifier, expression):
let type = try expression.staticType(in: context) ??
expression.evaluate(in: context).type
options[identifier.name] = type
case .define:
try statement.evaluate(in: context)
case .command, .forloop, .ifelse, .expression, .import:
break
}
}
}
let source = context.source
let baseURL = context.baseURL
return .block(.custom(.user, options)) { _context in
do {
let context = context.pushDefinition()
context.stackDepth = _context.stackDepth + 1
if context.stackDepth > 25 {
throw RuntimeErrorType.assertionFailure("Too much recursion")
}
for (name, symbol) in _context.userSymbols {
context.define(name, as: symbol)
}
context.children += _context.children
context.name = _context.name
context.material = _context.material
context.font = _context.font
context.transform = _context.transform
context.opacity = _context.opacity
context.detail = _context.detail
context.smoothing = _context.smoothing
context.baseURL = baseURL
context.source = source
for statement in block.statements {
if case let .option(identifier, expression) = statement.type {
if context.symbol(for: identifier.name) == nil {
context.define(
identifier.name,
as: .constant(try expression.evaluate(in: context))
)
}
} else {
try statement.evaluate(in: context)
}
}
let children = context.children
if children.count == 1, let value = children.first {
switch value {
case let .path(path):
guard context.name.isEmpty else {
return .mesh(Geometry(
type: .path(path),
name: context.name,
transform: context.transform,
material: .default,
smoothing: nil,
children: [],
sourceLocation: context.sourceLocation
))
}
return .path(path.transformed(by: context.transform))
case let .mesh(geometry):
return .mesh(Geometry(
type: geometry.type,
name: context.name,
transform: geometry.transform * context.transform,
material: geometry.material,
smoothing: geometry.smoothing,
children: geometry.children,
sourceLocation: context.sourceLocation,
debug: geometry.debug
))
default:
if context.name.isEmpty {
return value
}
throw RuntimeErrorType.assertionFailure(
"Blocks that return a \(value.type.errorDescription) " +
"value cannot be assigned a name"
)
}
} else if context.name.isEmpty,
// Manage backwards compatibility for blocks that return
// multiple meshes to be used inside difference block
!children.contains(where: { $0.type == .mesh }) ||
children.contains(where: { ![.mesh, .path].contains($0.type) })
{
return .tuple(children.map {
switch $0 {
case let .path(path):
return .path(path.transformed(by: context.transform))
case let .mesh(geometry):
return .mesh(geometry.transformed(by: context.transform))
default:
return $0
}
})
}
return .mesh(Geometry(
type: .group,
name: context.name,
transform: context.transform,
material: .default,
smoothing: context.smoothing,
children: try children.map {
switch $0 {
case let .path(path):
return Geometry(
type: .path(path),
name: nil,
transform: .identity,
material: .default,
smoothing: nil,
children: [],
sourceLocation: context.sourceLocation
)
case let .mesh(geometry):
return geometry
default:
throw RuntimeErrorType.assertionFailure(
"Blocks that return a \($0.type.errorDescription) " +
"value cannot be assigned a name"
)
}
},
sourceLocation: context.sourceLocation
))
} catch var error {
if let e = error as? RuntimeError,
case let .unknownSymbol(name, options: options) = e.type
{
// TODO: find a less hacky way to limit the scope of option keyword
error = RuntimeError(
.unknownSymbol(name, options: options + ["option"]),
at: e.range
)
}
if baseURL == _context.baseURL {
throw error
}
throw RuntimeErrorType.importError(
ImportError(error),
for: baseURL?.lastPathComponent ?? "",
in: source
)
}
}
}
}
}
extension EvaluationContext {
func addValue(_ value: Value) throws {
switch value {
case _ where childTypes.contains { value.isConvertible(to: $0) }:
switch value {
case let .mesh(m):
children.append(.mesh(m.transformed(by: childTransform)))
case let .vector(v):
children.append(.vector(v.transformed(by: childTransform)))
case let .point(v):
children.append(.point(v.transformed(by: childTransform)))
case let .path(path):
children.append(.path(path.transformed(by: childTransform)))
case _ where !childTypes.contains(value.type) && childTypes.contains(.text):
children.append(.text(TextValue(
string: value.stringValue,
font: font,
color: material.color,
linespacing: self.value(for: "linespacing")?.doubleValue
)))
case let .tuple(values) where values.count <= 1:
children += values
default:
children.append(value)
}
case let .path(path) where childTypes.contains(.mesh):
children.append(.mesh(Geometry(
type: .path(path),
name: name,
transform: childTransform,
material: .default, // not used for paths
smoothing: nil,
children: [],
sourceLocation: sourceLocation
)))
case let .tuple(values):
try values.forEach(addValue)
default:
throw RuntimeErrorType.unusedValue(type: value.type.errorDescription)
}
}
}
extension Statement {
func evaluate(in context: EvaluationContext) throws {
switch type {
case let .command(identifier, parameter):
let name = identifier.name
guard let symbol = context.symbol(for: name) else {
throw RuntimeError(
.unknownSymbol(name, options: context.commandSymbols),
at: identifier.range
)
}
switch symbol {
case let .command(type, fn):
let argument = try evaluateParameter(parameter,
as: type,
for: identifier,
in: context)
try RuntimeError.wrap(fn(argument, context), at: range)
case let .function(type, fn):
let argument = try evaluateParameter(parameter,
as: type,
for: identifier,
in: context)
try RuntimeError.wrap(context.addValue(fn(argument, context)), at: range)
case let .property(type, setter, _):
let argument = try evaluateParameter(parameter,
as: type,
for: identifier,
in: context)
try RuntimeError.wrap(setter(argument, context), at: range)
case let .block(type, fn):
context.sourceIndex = range.lowerBound
if let parameter = parameter {
func unwrap(_ value: Value) -> Value {
if case let .tuple(values) = value {
if values.count == 1 {
return unwrap(values[0])
}
return .tuple(values.map(unwrap))
} else {
return value
}
}
let parameters: [Expression]
if case let .tuple(expressions) = parameter.type {
parameters = expressions
} else {
parameters = [parameter]
}
var children = try evaluateParameters(
parameters,
in: context
).map(unwrap)
if children.count == 1, case let .tuple(values) = children[0] {
children = values
}
for child in children where !type.childTypes
.contains(where: child.isConvertible)
{
// TODO: can we highlight specific argument?
throw RuntimeError(.typeMismatch(
for: name,
index: 0,
expected: type.childTypes.map { $0.errorDescription } + ["block"],
got: child.type.errorDescription
), at: parameter.range)
}
try RuntimeError.wrap({
let childContext = context.push(type)
childContext.userSymbols.removeAll()
try children.forEach(childContext.addValue)
try context.addValue(fn(childContext))
}(), at: range)
} else if !type.childTypes.isEmpty {
throw RuntimeError(
.missingArgument(for: name, index: 0, type: "block"),
at: range
)
} else {
let childContext = context.push(type)
childContext.userSymbols.removeAll()
try RuntimeError.wrap(context.addValue(fn(childContext)), at: range)
}
case let .constant(v):
try RuntimeError.wrap(context.addValue(v), at: range)
}
case let .expression(expression):
try RuntimeError.wrap(context.addValue(expression.evaluate(in: context)), at: range)
case let .define(identifier, definition):
context.define(identifier.name, as: try definition.evaluate(in: context))
case .option:
throw RuntimeError(.unknownSymbol("option", options: []), at: range)
case let .forloop(identifier, in: expression, block):
let value = try expression.evaluate(in: context)
guard let sequence = value.sequenceValue else {
throw RuntimeError(
.typeMismatch(
for: "range",
index: 0,
expected: ["range", "tuple"],
got: value.type.errorDescription
),
at: expression.range
)
}
for value in sequence {
if context.isCancelled() {
throw EvaluationCancelled()
}
try context.pushScope { context in
if let name = identifier?.name {
context.define(name, as: .constant(value))
}
for statement in block.statements {
try statement.evaluate(in: context)
}
}
}
case let .ifelse(condition, body, else: elseBody):
let value = try condition.evaluate(as: .boolean, for: "condition", index: 0, in: context)
try context.pushScope { context in
if value.boolValue {
for statement in body.statements {
try statement.evaluate(in: context)
}
} else if let elseBody = elseBody {
for statement in elseBody.statements {
try statement.evaluate(in: context)
}
}
}
case let .import(expression):
let pathValue = try expression.evaluate(
as: .string,
for: Keyword.import.rawValue,
in: context
)
let path = pathValue.stringValue
context.sourceIndex = expression.range.lowerBound
try RuntimeError.wrap(context.importModel(at: path), at: expression.range)
}
}
}
extension Expression {
func staticType(in context: EvaluationContext) throws -> ValueType? {
switch type {
case .number:
return .number
case .string:
return .string
case .color:
return .color
case let .identifier(name):
guard let symbol = context.symbol(for: name) else {
throw RuntimeError(
.unknownSymbol(name, options: context.expressionSymbols),
at: range
)
}
switch symbol {
case .command:
return .void
case .function, .block:
return nil
case let .property(type, _, _):
return type
case let .constant(value):
return value.type
}
case let .block(identifier, block):
let (name, range) = (identifier.name, identifier.range)
guard let symbol = context.symbol(for: name) else {
throw RuntimeError(.unknownSymbol(name, options: context.expressionSymbols), at: range)
}
switch symbol {
case .command:
return .void
case .block, .function:
return nil
case .property, .constant:
throw RuntimeError(
.unexpectedArgument(for: name, max: 0),
at: block.range
)
}
case let .tuple(expressions) where expressions.count == 1:
// TODO: find better solution for this
return try expressions[0].staticType(in: context)
case .tuple:
return .tuple
case .prefix(.minus, _),
.prefix(.plus, _),
.infix(_, .minus, _),
.infix(_, .plus, _),
.infix(_, .times, _),
.infix(_, .divide, _):
return .number
case .infix(_, .to, _), .infix(_, .step, _):
return .range
case .infix(_, .equal, _),
.infix(_, .unequal, _),
.infix(_, .lt, _),
.infix(_, .gt, _),
.infix(_, .lte, _),
.infix(_, .gte, _),
.infix(_, .and, _),
.infix(_, .or, _):
return .boolean
case .member:
// TODO: This should be possible to get
return nil
case let .subexpression(expression):
return try expression.staticType(in: context)
}
}
func evaluate(in context: EvaluationContext) throws -> Value {
switch type {
case let .number(number):
return .number(number)
case let .string(string):
return .string(string)
case let .color(color):
return .color(color)
case let .identifier(name):
guard let symbol = context.symbol(for: name) else {
throw RuntimeError(
.unknownSymbol(name, options: context.expressionSymbols),
at: range
)
}
switch symbol {
case .command:
// Commands can't be used in expressions
throw RuntimeError(
.unknownSymbol(name, options: context.expressionSymbols),
at: range
)
case let .function(parameterType, fn):
guard parameterType == .void else {
// Functions with parameters can't be called without arguments
throw RuntimeError(.missingArgument(
for: name,
index: 0,
type: parameterType.errorDescription
), at: range.upperBound ..< range.upperBound)
}
return try RuntimeError.wrap(fn(.void, context), at: range)
case let .property(_, _, getter):
return try RuntimeError.wrap(getter(context), at: range)
case let .block(type, fn):
guard type.childTypes.isEmpty else {
// Blocks that require children can't be called without arguments
throw RuntimeError(.missingArgument(
for: name,
index: 0,
type: "block"
), at: range.upperBound ..< range.upperBound)
}
return try RuntimeError.wrap(fn(context.push(type)), at: range)
case let .constant(value):
return value
}
case let .block(identifier, block):
let (name, range) = (identifier.name, identifier.range)
guard let symbol = context.symbol(for: name) else {
throw RuntimeError(.unknownSymbol(name, options: context.expressionSymbols), at: range)
}
switch symbol {
case let .block(type, fn):
if context.isCancelled() {
throw EvaluationCancelled()
}
let sourceIndex = context.sourceIndex
let context = context.push(type)
for statement in block.statements {
switch statement.type {
case let .command(identifier, parameter):