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
1643 lines (1605 loc) · 67 KB
/
Interpreter.swift
File metadata and controls
1643 lines (1605 loc) · 67 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.8.5"
public func evaluate(
_ program: Program,
delegate: EvaluationDelegate?,
cache: GeometryCache? = GeometryCache(),
isCancelled: @escaping () -> Bool = { false }
) throws -> Scene {
let (scene, error) = evaluate(
program,
delegate: delegate,
cache: cache,
isCancelled: isCancelled
)
if let error = error {
throw error
}
return scene
}
@_disfavoredOverload
public func evaluate(
_ program: Program,
delegate: EvaluationDelegate?,
cache: GeometryCache?,
isCancelled: @escaping () -> Bool
) -> (Scene, Error?) {
let context = EvaluationContext(
source: program.source,
delegate: delegate,
isCancelled: isCancelled
)
let result = Result { try program.evaluate(in: context) }
let scene = Scene(
background: context.background ?? .color(.clear),
children: context.children.compactMap { $0.value as? Geometry },
cache: cache
)
switch result {
case .success:
return (scene, nil)
case let .failure(error):
return (scene, error)
}
}
public enum RuntimeErrorType: Error, Equatable {
case unknownSymbol(String, options: [String])
case unknownMember(String, of: String, options: [String])
case invalidIndex(Double, range: Range<Int>)
case unknownFont(String, options: [String])
case typeMismatch(for: String, index: Int, expected: String, got: String)
case forwardReference(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 fileTimedOut(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)
case circularImport(for: URL)
indirect case importError(ProgramError, for: URL?, 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, name != "option" {
return "Unknown symbol '\(name)'"
}
return "Unexpected symbol '\(name)'"
case let .unknownMember(name, type, _):
return "Member '\(name)' not found for \(type)"
case let .invalidIndex(index, _):
return "Index \(index.logDescription) out of bounds"
case let .unknownFont(name, _):
return name.isEmpty ? "Font name cannot be blank" : "Unknown font '\(name)'"
case .typeMismatch:
return "Type mismatch"
case .forwardReference:
return "Forward reference"
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 .fileTimedOut(for: name, _):
return "File '\(name)' timed out"
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 .circularImport:
return "Circular import"
case let .importError(error, for: url, _):
if case let .runtimeError(error) = error, case .importError = error.type {
return error.message
}
let name = url.map { " '\($0.lastPathComponent)'" } ?? ""
let error = error.range.map { _ in ": \(error.message)" } ?? ""
return "Error in imported file\(name)\(error)"
}
}
var suggestion: String? {
switch type {
case let .unknownSymbol(name, options), let .unknownMember(name, _, options):
let alternative = Self.alternatives[name.lowercased()]?
.first(where: { options.contains($0) || Keyword(rawValue: $0) != nil })
if Symbols.all[name] != nil {
return alternative
}
let ordinals = !name.isOrdinal && options.contains { $0.isOrdinal } ? String.ordinals : []
return alternative ?? name.bestMatches(in: options + ordinals).first
case let .unknownFont(name, options):
return name.bestMatches(in: options).first
case .typeMismatch,
.forwardReference,
.unexpectedArgument,
.missingArgument,
.invalidIndex,
.unusedValue,
.assertionFailure,
.fileNotFound,
.fileTimedOut,
.fileAccessRestricted,
.fileTypeMismatch,
.fileParsingError,
.circularImport,
.importError:
return nil
}
}
var hint: String? {
func nthArgument(_ index: Int) -> String {
switch index {
case 0 ..< String.ordinals.count:
return "\(String.ordinals[index]) argument"
default:
return "argument"
}
}
func theSymbol(_ name: String) -> String {
if name.components(separatedBy: " ").count == 2 {
return "The \(name)"
} else if name.isEmpty {
return "Symbol"
} else if let symbol = Symbols.all[name] {
return "The \(name) \(symbol.errorDescription)"
}
return "The \(name) symbol"
}
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 || name == "option" {
hint = "The \(name) command is not available in this context."
}
if let suggestion = suggestion {
hint += (hint.isEmpty ? "" : " ") + "Did you mean '\(suggestion)'?"
}
return hint
case let .unknownMember(name, of: _, options: options):
if let index = name.ordinalIndex, index > 0 {
for i in (0 ..< index).reversed() where options.contains(String.ordinals[i]) {
guard String.ordinals(upTo: i).allSatisfy(options.contains) else {
break
}
return "Valid range is 'first' to '\(String.ordinals[i])'."
}
}
return suggestion.map { "Did you mean '\($0)'?" }
case let .invalidIndex(_, range: range):
return range.upperBound == 0 ? nil : "Valid range is \(range.lowerBound) to \(range.upperBound - 1)."
case .unknownFont:
if let suggestion = suggestion {
return "Did you mean '\(suggestion)'?"
}
return ""
case let .typeMismatch(for: name, index: i, expected: type, got: got):
let name = [
"if condition",
"loop bounds",
"step value",
].contains(name) ? name : "\(nthArgument(i)) for \(name)"
let got = got.contains(",") ? got : aOrAn(got)
return "The \(name) should be \(aOrAn(type)), not \(got)."
case let .forwardReference(name):
return "The symbol '\(name)' was used before it was defined."
case let .unexpectedArgument(for: name, max: max):
if max == 0 {
return "\(theSymbol(name)) does not expect any arguments."
} else if max == 1 {
return "\(theSymbol(name)) expects only a single argument."
} else {
return "\(theSymbol(name)) expects a maximum of \(max) arguments."
}
case let .missingArgument(for: name, index: i, type: type):
let type = (type == ValueType.any.errorDescription) ? "" : " of type \(type)"
return "\(theSymbol(name)) expects \(aOrAn(nthArgument(i > 0 ? i : -1)))\(type)."
case let .unusedValue(type: type):
return "\(aOrAn(type, capitalized: true)) 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 .fileTimedOut(for: _, at: url):
return "ShapeScript was unable to download the file at '\(url.path)'."
+ " Check your network settings."
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 \(aOrAn(type)) file."
case .circularImport:
return "Files cannot import themselves."
case let .importError(error, for: _, in: _):
if error.range == nil {
return error.message
}
return error.hint
}
}
var accessErrorURL: URL? {
switch type {
case let .fileAccessRestricted(for: _, at: url):
return url
case let .importError(error, _, _):
return error.accessErrorURL
case .typeMismatch,
.forwardReference,
.unexpectedArgument,
.missingArgument,
.unusedValue,
.assertionFailure,
.fileNotFound,
.fileTimedOut,
.fileTypeMismatch,
.fileParsingError,
.circularImport,
.unknownSymbol,
.unknownMember,
.invalidIndex,
.unknownFont:
return nil
}
}
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 func aOrAn(_ string: String, capitalized: Bool = false) -> String {
guard let first = string.first else {
return capitalized ? "An" : "an"
}
let beginsWithVowel = "AEIOUaeiou".contains(first)
let prefix = beginsWithVowel ? "an" : "a"
return "\(capitalized ? prefix.capitalized : prefix) \(string)"
}
private extension Array where Element == String {
var typesDescription: String {
var types = Set(self).sorted()
if let index = types.firstIndex(of: "block") {
types.append(types.remove(at: index))
}
switch types.count {
case 1:
return types[0]
case 2:
return "\(types[0]) or \(types[1])"
default:
return "\(types.dropLast().joined(separator: ", ")), or \(types.last!)"
}
}
}
extension RuntimeErrorType {
static func typeMismatch(
for symbol: String,
expected: String,
got: String
) -> RuntimeErrorType {
.typeMismatch(for: symbol, index: -1, expected: expected, got: got)
}
static func typeMismatch(
for symbol: String,
index: Int = -1,
expected types: [String],
got: String
) -> RuntimeErrorType {
let expected = types.typesDescription
return .typeMismatch(for: symbol, index: index, expected: expected, got: got)
}
static func typeMismatch(
for name: String,
index: Int = -1,
expected: ValueType,
got: ValueType
) -> RuntimeErrorType {
let typeDescription: String
switch expected {
case let .list(type):
typeDescription = type.errorDescription
case let .tuple(types) where !types.isEmpty:
typeDescription = types[0].errorDescription
default:
typeDescription = expected.errorDescription
}
return typeMismatch(
for: name,
index: index,
expected: typeDescription,
got: got.errorDescription
)
}
static func missingArgument(
for symbol: String,
type: String
) -> RuntimeErrorType {
.missingArgument(for: symbol, index: 0, type: type)
}
static func missingArgument(
for symbol: String,
index: Int = 0,
types: [String]
) -> RuntimeErrorType {
let expected = types.typesDescription
return .missingArgument(for: symbol, index: index, type: expected)
}
static func missingArgument(
for name: String,
index: Int = 0,
type: ValueType
) -> RuntimeErrorType {
let typeDescription: String
switch type {
case let .list(type):
typeDescription = type.errorDescription
case let .tuple(types) where !types.isEmpty:
typeDescription = types[0].errorDescription
default:
typeDescription = type.errorDescription
}
return missingArgument(for: name, index: index, type: typeDescription)
}
static func unusedValue(type: ValueType) -> RuntimeErrorType {
let typeDescription: String
switch type {
case let .list(type):
typeDescription = type.errorDescription
default:
typeDescription = type.errorDescription
}
return unusedValue(type: typeDescription)
}
static func unknownMember(_ name: String, of value: Value) -> RuntimeErrorType {
// TODO: find less hacky way to do this unwrap
var value = value
while case let .tuple(values) = value, values.count == 1 {
value = values[0]
}
assert(!value.members.contains(name),
"\(value.errorDescription) should have member '\(name)'")
return unknownMember(name, of: value.errorDescription, options: value.members)
}
static func fileError(_ error: Error, for path: String, at url: URL) -> RuntimeErrorType {
var error = error
while let nsError = error as NSError? {
if nsError.domain == NSCocoaErrorDomain, nsError.code == 259 {
// Not a recognized model file format
break
}
var underlyingError: Error?
#if !os(Linux)
if #available(macOS 11.3, iOS 14.5, tvOS 14.5, *) {
underlyingError = nsError.underlyingErrors.first
}
#endif
underlyingError = underlyingError ?? nsError.userInfo[NSUnderlyingErrorKey] as? Error
if let underlyingError = underlyingError {
error = underlyingError
} else {
break
}
}
return RuntimeErrorType.fileParsingError(
for: path, at: url, message: error.localizedDescription
)
}
}
private extension RuntimeError {
static let alternatives: [String: [String]] = [
"box": ["cube"],
"rect": ["square"],
"rectangle": ["square"],
"triangle": ["polygon"],
"ellipse": ["circle"],
"elipse": ["circle"],
"squircle": ["roundrect"],
"rotate": ["orientation"],
"rotation": ["orientation"],
"orientation": ["rotate"],
"translate": ["position"],
"translation": ["position"],
"position": ["translate", "bounds", "center"],
"faces": ["polygons"],
"triangles": ["polygons"],
"vertices": ["points"],
"scale": ["size"],
"size": ["scale", "bounds"],
"width": ["size", "x"],
"height": ["size", "y"],
"depth": ["size", "z"],
"length": ["size", "count"],
"magnitude": ["length"],
"norm": ["length"],
"radius": ["size"],
"sine": ["sin"],
"cosine": ["cos"],
"x": ["width", "position"],
"y": ["height", "position"],
"z": ["depth", "position"],
"option": ["define"],
"subtract": ["difference"],
"subtraction": ["difference"],
"sweep": ["extrude"],
"head": ["first"],
"tail": ["last", "allButFirst"],
"rest": ["allButFirst"],
"rands": ["rnd", "seed"],
"rand": ["rnd"],
"random": ["rnd"],
"noise": ["rnd"],
"signum": ["sign"],
"echo": ["print"],
"default": ["else"],
"metalness": ["metallicity"],
"metallicness": ["metallicity"],
"smoothness": ["roughness"],
"emission": ["glow"],
"emissiveness": ["glow"],
].merging(ParserError.alternatives.mapValues { [$0] }) { $1 }
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
}()
}
extension Program {
func evaluate(in context: EvaluationContext) throws {
let oldSource = context.source
let oldSourceIndex = context.sourceIndex
let oldBaseURL = context.baseURL
context.source = source
context.sourceIndex = nil
context.baseURL = fileURL ?? oldBaseURL
defer {
context.source = oldSource
context.sourceIndex = oldSourceIndex
context.baseURL = oldBaseURL
}
statements.gatherDefinitions(in: context)
do {
try statements.forEach { try $0.evaluate(in: context) }
} catch is EvaluationCancelled {}
}
}
private func evaluateParameters(
_ parameters: [Expression],
in context: EvaluationContext
) throws -> [(index: Int, value: Value)] {
var values = [(Int, 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((i, 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 {
switch try fn(arg, context) {
case let .tuple(tuple):
values += tuple.map { (i, $0) }
case let value:
values.append((i, value))
}
} 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 != .void:
let parameters = Array(parameters[(i + 1)...])
let childContext = context.push(type)
childContext.userSymbols.removeAll()
let identifier = Identifier(name: name, range: param.range)
try evaluateBlockParameters(
parameters, for: identifier,
type: type, in: context, childContext
)
try RuntimeError.wrap(values.append((i, fn(childContext))), at: param.range)
break loop
case .function, .block, .property, .constant, .option, .placeholder:
try values.append((i, param.evaluate(in: context)))
}
}
return values
}
private func evaluateBlockParameters(
_ parameters: [Expression],
for identifier: Identifier,
type: BlockType,
in context: EvaluationContext,
_ childContext: EvaluationContext
) throws {
guard let first = parameters.first, let last = parameters.last else {
return
}
let range = first.range.lowerBound ..< last.range.upperBound
let children: [(Int, Value)]
if type.childTypes.subtypes.contains(.text) {
let param = Expression(type: .tuple(parameters), range: range)
do {
children = try [(0, param.evaluate(as: .text, for: identifier.name, in: context))]
} catch {
children = try evaluateParameters(parameters, in: context)
}
} else {
children = try evaluateParameters(parameters, in: context)
}
for (j, child) in children {
do {
try childContext.addValue(child)
} catch {
var types = type.childTypes.subtypes.map { $0.errorDescription }
if j == 0 {
types.append("block")
}
throw RuntimeError(
.typeMismatch(
for: identifier.name,
index: j > 0 ? j : -1,
expected: types,
got: child.type.errorDescription
),
at: j < parameters.count ? parameters[j].range : range
)
}
}
}
// 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.isOptional {
return .void
}
throw RuntimeError(
.missingArgument(for: name, type: type),
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
let returnType: ValueType
var params = Dictionary(uniqueKeysWithValues: names.map {
($0.name, ValueType.any)
})
do {
let context = context.push(.init(.all, [:], .any, .any))
block.inferTypes(for: ¶ms, in: context)
for (name, type) in params {
context.define(name, as: .placeholder(type))
}
returnType = try block.staticType(in: context)
}
let paramTypes = names.map { params[$0.name] ?? .any }
return .function(.tuple(paramTypes), returnType) { value, context in
do {
let oldChildren = context.children
let oldChildTypes = context.childTypes
let oldSymbols = context.userSymbols
let oldSource = context.source
let oldBaseURL = context.baseURL
let wasFunctionScope = context.isFunctionScope
context.children = []
context.childTypes = .any
context.source = declarationContext.source
context.baseURL = declarationContext.baseURL
context.userSymbols = declarationContext.userSymbols
context.stackDepth += 1
context.isFunctionScope = true
defer {
context.children = oldChildren
context.childTypes = oldChildTypes
context.source = oldSource
context.baseURL = oldBaseURL
context.userSymbols = oldSymbols
context.stackDepth -= 1
context.isFunctionScope = wasFunctionScope
}
if context.stackDepth > 25 {
throw RuntimeErrorType.assertionFailure("Too much recursion")
}
let values: [Value]
if case let .tuple(_values) = value {
values = _values
} else {
values = [value]
}
assert(values.count == names.count)
for (identifier, value) in zip(names, values) {
context.define(identifier.name, as: .constant(value))
}
try block.evaluate(in: context)
if context.children.count == 1 {
return context.children[0]
}
return .tuple(context.children)
} catch {
if declarationContext.baseURL == context.baseURL {
throw error
}
throw RuntimeErrorType.importError(
ProgramError(error),
for: declarationContext.baseURL,
in: declarationContext.source
)
}
}
case let .block(block):
var options: Options? = [:]
let returnType: ValueType
do {
let context = context.push(.init(.definition, [:], .void, .any))
returnType = try block.staticType(in: context, options: &options)
} catch var error as RuntimeError {
if case let .unknownSymbol(name, options: options) = error.type {
// TODO: find a less hacky way to limit the scope of option keyword
error = RuntimeError(
.unknownSymbol(name, options: options + ["option"]),
at: error.range
)
}
throw error
}
let source = context.source
let sourceIndex = context.sourceIndex
let baseURL = context.baseURL
return .block(.init(.user, options ?? [:], .void, returnType)) { _context in
do {
let context = context.pushDefinition()
context.stackDepth = _context.stackDepth + 1
if context.stackDepth > 48 {
throw RuntimeErrorType.assertionFailure("Too much recursion")
}
for (name, symbol) in _context.userSymbols {
switch symbol {
case .option:
// Only options are copied from call scope
context.define(name, as: symbol)
case .block, .function, .property, .constant, .placeholder:
break
}
}
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
context.sourceIndex = sourceIndex
block.statements.gatherDefinitions(in: context)
for statement in block.statements {
if case let .option(identifier, expression) = statement.type {
if case .option? = context.symbol(for: identifier.name) {
// Ignore default
} else {
try context.define(
identifier.name,
as: .constant(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
))
case let .polygon(polygon):
return .polygon(polygon.transformed(by: context.transform))
default:
if context.name.isEmpty {
return value
}
throw RuntimeErrorType.assertionFailure(
"Blocks that return \(aOrAn(value.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 try .mesh(Geometry(
type: .group,
name: context.name,
transform: context.transform,
material: .default,
smoothing: context.smoothing,
children: 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 \(aOrAn($0.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(
ProgramError(error),
for: baseURL,
in: source
)
}
}
}
}
}
extension EvaluationContext {
func addValue(_ value: Value) throws {
if let value = try value.as(childTypes, in: self) {
let childTransform: Transform = isFunctionScope ? .identity : self.childTransform
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(p):
children.append(.point(p.transformed(by: childTransform)))
case let .polygon(p):
children.append(.polygon(p
.transformed(by: childTransform)
.fixupColors(material: material)))
case let .path(path):
children.append(.path(path.transformed(by: childTransform)))
case _ where childTypes.subtypes.contains(.text):
children.append(.text(TextValue(
string: value.stringValue,
font: self.value(for: "font")?.stringValue ?? font,
color: material.color,
linespacing: self.value(for: "linespacing")?.doubleValue
)))
case .void:
break
default:
children.append(value)
}
} else if case let .tuple(values) = value {
try values.forEach(addValue)
} else {
throw RuntimeErrorType.unusedValue(type: value.type)
}
}
}
extension Block {
func evaluate(in context: EvaluationContext) throws {
statements.gatherDefinitions(in: context)
try statements.forEach { try $0.evaluate(in: context) }
}
}
extension Statement {
func evaluate(in context: EvaluationContext) throws {
let sourceIndex = context.sourceIndex
context.sourceIndex = range.lowerBound
defer {
context.sourceIndex = sourceIndex
}
switch type {
case let .command(identifier, parameter):
var name = identifier.name
if let type = context.options[name] ?? {
if name == "colour", let type = context.options["color"] {
name = "color"
return type
}
if let type = context.options["*"] {
context.options[name] = .any
return type
}
return nil
}() {
return try context.define(name, as: .option(
evaluateParameter(parameter,
as: type,
for: identifier,
in: context)
))
}
guard let symbol = context.symbol(for: name) else {
throw RuntimeError(
.unknownSymbol(name, options: context.commandSymbols),
at: identifier.range
)
}
switch symbol {
case let .function((parameterType, _), fn):