forked from PekanMmd/Pokemon-XD-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XDSExtensions.swift
1834 lines (1576 loc) · 49 KB
/
XDSExtensions.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
//
// XDSExtensions.swift
// GoD Tool
//
// Created by The Steez on 22/10/2018.
//
import Foundation
extension XDSScriptCompiler {
class func syntacticSugarVariableXDS() -> String {
// a variable that is likely to be unique
// and can be programmatically generated
// useful for if statements to add in locations
let variable = "__XDS_SyntacticSugar_Variable_\(XDSScriptCompiler.sugarVarCounter)"
XDSScriptCompiler.sugarVarCounter += 1
return variable
}
class func stripWhiteSpaceXDS(text: String) -> String? {
var stripped = ""
let stack = text.stack
enum WhiteSpaceScopes {
case space
case newLine
case string
case normal
}
var scope = WhiteSpaceScopes.normal
// remove leading new lines
if !stack.isEmpty {
var done = false
while !done {
if stack.peek() == "\n" {
stack.popVoid()
} else {
done = true
}
if stack.isEmpty {
done = true
}
}
}
// strips consecutive white space characters
// also combine multiline statements into one line if contained within brackets by treating newlines as
// regular spaces.
// doesn't include vector brackets ('<' or '>') as they also serve as greater/less than operators
var bracketLevel = 0
let leftBrackets = "([{"
let rightBrackets = ")]}"
let bracketStack = XGStack<String>()
while !stack.isEmpty {
if leftBrackets.contains(stack.peek()) {
bracketLevel += 1
bracketStack.push(stack.peek())
}
if bracketLevel > 0 {
if rightBrackets.contains(stack.peek()) {
bracketLevel -= 1
}
let right = stack.peek()
let left = bracketStack.peek()
if right == "}" && left == "{" {
bracketStack.popVoid()
} else if right == "]" && left == "[" {
bracketStack.popVoid()
} else if right == ")" && left == "(" {
bracketStack.popVoid()
} else {
error = "Error: Unclosed '\(left)' bracket in text."
}
}
// replace newlines with regular spaces if within brackets
// replace with semi colons if within curly braces
if bracketLevel > 0 {
if stack.peek() == "\n" {
stack.popVoid()
if bracketStack.peek() == "{" {
stack.push(";")
} else {
stack.push(" ")
}
}
}
var ignore = false
if scope == .space {
if stack.peek() == " " {
ignore = true
} else if stack.peek() == "\n" {
scope = .newLine
} else if stack.peek() == "\"" {
scope = .string
} else {
scope = .normal
}
} else if scope == .newLine {
if (stack.peek() == "\n") || (stack.peek() == " ") {
ignore = true
} else if stack.peek() == "\"" {
scope = .string
} else {
scope = .normal
}
} else if scope == .string {
if stack.peek() == "\"" {
scope = .normal
}
} else {
if stack.peek() == " " {
scope = .space
} else if stack.peek() == "\n" {
scope = .newLine
} else if stack.peek() == "\"" {
scope = .string
}
}
let current = stack.pop()
if !ignore {
stripped += current
}
}
// remove all spaces at end of line
// also remove spaces immediately following or preceding brackets
for (replace, with) in [(" \n","\n"),("[ ","["),("( ","("),(" ]","]"),(" )",")")] {
while stripped.range(of: replace) != nil {
stripped = stripped.replacingOccurrences(of: replace, with: with)
}
}
if stripped.length > 0 {
while "\n ".contains(stripped.last!) {
stripped.removeLast()
}
}
return stripped
}
class func stripCommentsXDS(text: String) -> String {
var stripped = ""
let stack = text.stack
enum CommentScopes {
case singleLine
case multiLine
case string
case normal
}
var scope = CommentScopes.normal
while !stack.isEmpty {
let currentChar = stack.pop()
if scope == .singleLine {
if currentChar == "\n" {
scope = .normal
stripped += "\n"
}
continue
} else if scope == .multiLine {
if currentChar == "*" && stack.peek() == "/" {
stack.popVoid()
scope = .normal
}
continue
} else if scope == .string {
if currentChar == "\"" {
scope = .normal
}
stripped += currentChar
continue
} else {
if currentChar == "/" && stack.peek() == "/" {
scope = .singleLine
stack.popVoid()
continue
} else if currentChar == "/" && stack.peek() == "*" {
scope = .multiLine
stack.popVoid()
continue
} else if currentChar == "\"" {
scope = .string
stripped += "\""
continue
} else {
stripped += currentChar
}
}
}
return stripped
}
class func getLinesXDS(text: String) -> [String] {
let stack = text.stack
var lines = [String]()
var currentLine = ""
while !stack.isEmpty {
let currentChar = stack.pop()
if currentChar != "\n" {
currentLine += currentChar
} else {
lines.append(currentLine + "\n")
currentLine = ""
}
}
if currentLine.length > 0 {
lines.append(currentLine + "\n")
}
return lines
}
private class func parseLiteral(_ text: String) -> (XDSConstantTypes, [XDSConstant])? {
// returns a tuple
// first element has type vector if second element is 3 floats representing a vector literal
// first element has type array if second element is an array representing an array literal
// otherwise second element contains a single value representing a literal. The constant contains its type.
if text.length == 0 {
return nil
}
if text.first == "#" {
error = "Undefined Macro: \(text)"
return nil
}
if text.first! == "@" {
error = "Uh oh, location as a literal! Technically allowed but hoped this day would never come. If you wrote this line yourself then it's probably wrong otherwise tell @StarsMmd he has to implement location literals. \(text)"
return nil
}
if let val = text.integerValue {
return (XDSConstantTypes.integer, [XDSConstant.integer(val)])
}
if let val = Float(text) {
return (XDSConstantTypes.float, [XDSConstant.float(val)])
}
if "ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(text.substring(from: 0, to: 1)) {
if text.contains("(") && text.contains(")") {
if let type = XDSConstantTypes.typeWithName(text.functionName!) {
if let param = text.parameterString {
let paramString = param == "" ? "0" : param
if let val = paramString.integerValue {
return (type, [XDSConstant(type: type.index, rawValue:UInt32(val))])
}
}
}
}
}
if text == "Null" {
return (XDSConstantTypes.none_t, [XDSConstant.null])
}
if ["True", "Yes", "YES", "TRUE"].contains(text) {
return (XDSConstantTypes.integer, [XDSConstant.integer(1)])
}
if ["False", "No", "NO", "FALSE"].contains(text) {
return (XDSConstantTypes.integer, [XDSConstant.integer(0)])
}
if let index = arrys.names.index(of: text) {
return (XDSConstantTypes.none_t, [XDSConstant(type: XDSConstantTypes.array.index, rawValue: UInt32(index))])
}
if let index = vects.names.index(of: text) {
return (XDSConstantTypes.none_t, [XDSConstant(type: XDSConstantTypes.vector.index, rawValue: UInt32(index))])
}
if let index = giris.names.index(of: text) {
return (XDSConstantTypes.none_t, [XDSConstant(type: XDSConstantTypes.character.index, rawValue: UInt32(index))])
}
if text.substring(from: 0, to: 1) == "<" {
let parts = text.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "").split(separator: " ")
if parts.count == 3 {
if let x = Float(String(parts[0])) {
if let y = Float(String(parts[1])) {
if let z = Float(String(parts[2])) {
return (XDSConstantTypes.vector, [XDSConstant.float(x), XDSConstant.float(y), XDSConstant.float(z)])
}
}
}
}
}
if text.length > 2 {
if text.first! == "[" && text.last! == "]" {
var inner = text
inner.removeFirst()
inner.removeLast()
if let parts = tokeniseXDS(text: inner) {
var params = [XDSConstant]()
for token in parts {
if let (type, val) = parseLiteral(token) {
if type.index == XDSConstantTypes.array.index {
error = "Invalid array element, array cannot contain an array: \(token)"
return nil
}
params.append(val[0])
} else {
error = "Invalid array element: \(token)"
return nil
}
}
return (XDSConstantTypes.array, params)
} else {
return nil
}
}
}
if text.substring(from: 0, to: 1) == "$" {
let id = text.msgID
let str = text.msgText
if id != nil {
if id! < 0 {
error = "Invalid message id: \(text)"
return nil
}
}
if str != nil {
if str == "" {
error = "Invalid message id: \(text)"
return nil
}
}
if id == nil && str == nil {
error = "Invalid msg macro: \(text)"
return nil
}
let newID = str == nil ? id : handleMSGString(id: id, text: str!)
if newID != nil {
if newID! < 0 {
// error in handlemsg
return nil
}
return (XDSConstantTypes.integer, [XDSConstant.integer(newID!)])
}
}
return (XDSConstantTypes.none_t, [XDSConstant.null])
}
class func tokeniseXDS(text: String) -> [String]? {
// splits the line into individual tokens by spaces. spaces are ignored within brackets and strings so tokens like bracketed expressions or vector and string literals are considered one token.
enum BracketScopes : String {
case round = "("
case square = "["
case angled = "<"
case curly = "{"
case string = "\""
case normal = ""
var closing : String {
switch self {
case .round: return ")"
case .square: return "]"
case .angled: return ">"
case .curly: return "}"
case .string: return "\""
case .normal: return ""
}
}
}
let scopeStack = XGStack<BracketScopes>()
let stack = text.stack
var currentToken = ""
var tokens = [String]()
scopeStack.push(.normal)
while !stack.isEmpty {
let current = stack.pop()
if (current == " " && scopeStack.peek() == .normal) || (current == "\n" && scopeStack.peek() != .curly) {
tokens.append(currentToken)
currentToken = ""
} else if (current == ";" && scopeStack.peek() != .string && scopeStack.peek() != .curly) {
tokens.append(currentToken)
currentToken = ""
} else if scopeStack.peek() == .string {
if current == "\"" {
scopeStack.popVoid()
}
currentToken += current
} else if let bracket = BracketScopes(rawValue: current) {
var isOperator = false
if bracket == .angled {
if !stack.isEmpty {
if stack.peek() == " " || stack.peek() == "=" {
isOperator = true
}
}
}
if !isOperator {
scopeStack.push(bracket)
}
currentToken += current
} else {
for bracket : BracketScopes in [.round, .square, .angled, .curly] {
if current == bracket.closing {
var isOperator = false
if bracket == .angled {
if !stack.isEmpty {
if stack.peek() == " " || stack.peek() == "=" {
isOperator = true
}
}
}
if !isOperator {
if scopeStack.peek() == bracket {
scopeStack.popVoid()
} else {
if scopeStack.peek() != .string {
error = "Extraneous bracket: " + current + ". " + currentToken
return nil
}
}
}
}
}
currentToken += current
}
}
if currentToken.length > 0 {
tokens.append(currentToken)
}
if scopeStack.peek() != .normal {
error = "End of line without closing " + scopeStack.peek().rawValue + ". " + currentToken
return nil
}
return tokens.filter({ (s) -> Bool in
return s.length > 0
})
}
private class func handleSpecialMacro(tokens: [String]) -> Bool {
if tokens[1] == "++ScriptIdentifier" {
if let val = tokens[2].integerValue {
scriptID = val
return true
} else {
error = "Invalid script identifier value: \(tokens[0]) \(tokens[1]) \(tokens[2])"
return false
}
}
if tokens[1] == "++XDSVersion" {
if let val = Float(tokens[2]) {
xdsversion = val
if xdsversion > currentXDSVersion {
error = "This compiler is too old. It was built for xds versions \(String(format: "%1.1f", currentXDSVersion)) and below.\n"
error += "\(tokens[0]) \(tokens[1]) \(tokens[2])"
}
return true
} else {
error = "Invalid xds version: \(tokens[0]) \(tokens[1]) \(tokens[2])"
return false
}
}
if tokens[1] == "++BaseStringID" {
if let val = tokens[2].integerValue {
baseStringID = val
return true
} else {
error = "Invalid string id: \(tokens[0]) \(tokens[1]) \(tokens[2])"
return false
}
}
if tokens[1] == "++CreateBackup" {
if tokens[2] == "YES" || tokens[2] == "Yes" || tokens[2] == "TRUE" || tokens[2] == "True" {
createBackup = true
return true
} else if tokens[2] == "NO" || tokens[2] == "No" || tokens[2] == "FALSE" || tokens[2] == "False" {
createBackup = false
return true
} else {
error = "Invalid string id: \(tokens[0]) \(tokens[1]) \(tokens[2])"
return false
}
}
error = "Unrecognised special macro: \(tokens[1])"
return false
}
private class func handleAssignment(tokens: [String]) -> Bool {
//TODO: complete handle assignments character data
// don't forget to check for duplicate variable names
var flags = 0
var isVisible = true
var xCoordinate : Float = 0
var yCoordinate : Float = 0
var zCoordinate : Float = 0
var angle = 0
var hasScript = false
var scriptName = ""
var hasPassiveScript = false
var passiveScriptName = ""
var model = XGCharacterModels(index: 0)
var movementType = XGCharacterMovements.index(0)
var characterID = 0
var gid = -1
var rid = -1
var name = "" // just for sanity checking the variable, doesn't affect the character data
var assignIndex = 0
while assignIndex < tokens.count {
let token = tokens[assignIndex]
if assignIndex + 1 == tokens.count {
error = "Assignment variable missing value: \(token)"
return false
}
let nextToken = tokens[assignIndex + 1]
if nextToken.contains(":") {
error = "Assignment variable missing value: \(token)"
return false
}
switch token {
case "assign":
name = nextToken
case "GroupID:":
if let val = nextToken.integerValue {
gid = val
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "ResourceID:":
if let val = nextToken.integerValue {
rid = val
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "MovementID:":
if let val = nextToken.integerValue {
movementType = .index(val)
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "ModelID:":
if let val = nextToken.integerValue {
model = XGCharacterModels(index: val)
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "CharacterID:":
if let val = nextToken.integerValue {
characterID = val
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "Flags:":
if let val = nextToken.integerValue {
flags = val
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "Angle:":
if let val = nextToken.integerValue {
angle = val
while angle < 0 {
angle += 360
}
while angle >= 360 {
angle -= 360
}
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "X:":
if let val = Float(nextToken) {
xCoordinate = val
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "Y:":
if let val = Float(nextToken) {
yCoordinate = val
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "Z:":
if let val = Float(nextToken) {
zCoordinate = val
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "Script:":
let functionName = nextToken
if functionName.substring(from: 0, to: 1) == "@" && functionName.length > 1 {
scriptName = functionName
hasScript = true
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "Background:":
let functionName = nextToken
if functionName.substring(from: 0, to: 1) == "@" && functionName.length > 1 {
passiveScriptName = functionName
hasPassiveScript = true
} else {
error = "Invalid \(token) value: '\(nextToken)'"
return false
}
case "Visible:":
let b = nextToken
if ["YES", "TRUE", "Yes", "True"].contains(b) {
isVisible = true
} else if ["NO", "FALSE", "No", "False"].contains(b) {
isVisible = false
} else {
error = "Invalid assignment variable: \(token)"
return false
}
default:
error = "Invalid assignment variable: \(token)"
return false
}
assignIndex += 2
}
if name.length == 0 {
error = "Invalid assignment, missing variable name: "
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return false
}
if gid < 0 {
error = "Invalid assignment, missing group id: "
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return false
}
if rid < 0 {
error = "Invalid assignment, missing resource id: "
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return false
}
giris.names.append(name)
giris.values.append((groupID: gid, resourceID: rid))
if gid > 0 && rid >= 0 {
let character = XGCharacter()
character.angle = angle
character.xCoordinate = xCoordinate
character.yCoordinate = yCoordinate
character.zCoordinate = zCoordinate
character.characterID = characterID
character.movementType = movementType
character.hasScript = hasScript
character.hasPassiveScript = hasPassiveScript
character.flags = flags
character.isVisible = isVisible
character.model = model
character.scriptName = scriptName
character.passiveScriptName = passiveScriptName
character.gid = gid
character.rid = rid
characters.append(character)
}
return true
}
private class func handleGlobal(tokens: [String]) -> Bool {
if tokens.count != 4 {
error = "Incomplete global statement:"
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return false
}
if tokens[2] != "=" {
error = "Invalid global statement, missing '=':"
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return false
}
if !tokens[1].isValidXDSVariable() {
error = "Invalid global variable name '\(tokens[1])':"
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
error += "\n Variable names must only contain letters, numbers and underscores."
error += "\n Variable names must not begin with a number."
error += "\n Variable names must not begin with an uppercase character."
return false
}
if gvars.names.contains(tokens[1]) || giris.names.contains(tokens[1]) || arrys.names.contains(tokens[1]) || vects.names.contains(tokens[1]) {
error = "Global variable must have a unique name '\(tokens[1])':"
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return false
}
if tokens[1] == kXDSLastResultVariable {
error = "'\(kXDSLastResultVariable)' is a special reserved variable name."
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return false
}
if ["define", "call", "return", "function", "goto", "if", "ifnot", "Null", "global"].contains(tokens[1]) {
error = "'\(tokens[1])' is a reserved keyword."
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return false
}
if parseLiteral(tokens[3]) == nil {
error = "Invalid global variable value '\(tokens[3])':"
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return false
}
let (type, literal) = parseLiteral(tokens[3])!
switch type {
//TODO: confirm that .names.append() and .values.append() actually update the static vars
case .vector:
vects.names.append(tokens[1])
vects.values.append((literal[0].asFloat,literal[1].asFloat, literal[2].asFloat))
case .array:
arrys.names.append(tokens[1])
arrys.values.append(literal)
default:
gvars.names.append(tokens[1])
gvars.values.append(literal[0])
}
return true
}
class func macroprocessorXDS(text: String) -> String? {
var updated = ""
let lines = getLinesXDS(text: text)
var macros = [(macro: XDSMacro, replacement: String)]()
for line in lines {
var updatedLine = line
for (macro, repl) in macros {
for add in [" ", ".", ")", ">", "]", "(", "<", "[", "\"", "\n", "}", "{", ";"] {
updatedLine = updatedLine.replacingOccurrences(of: macro + add, with: repl + add)
}
}
if let tokens = tokeniseXDS(text: updatedLine) {
if tokens.count > 0 {
if tokens[0] == "define" {
// special define statements for compiler options
if tokens.count == 3 {
if tokens[1].contains("++") {
if !handleSpecialMacro(tokens: tokens) {
return nil
}
}
}
if tokens.count >= 3 {
let macro = tokens[1]
var replacement = tokens[2]
for i in 3 ..< tokens.count {
replacement += " " + tokens[i]
}
macros.append((macro: macro, replacement: replacement))
} else {
error = "Incomplete define statement: "
for i in 0 ..< tokens.count {
error += " " + tokens[i]
}
return nil
}
} else if tokens[0] == "assign" {
let newTokens = tokens.map({ (token) -> String in
var new = token
for (macro, repl) in macros {
new = new == macro ? repl : new
}
return new
})
if !handleAssignment(tokens: newTokens) {
return nil
}
} else if tokens[0] == "global" {
let newTokens = tokens.map({ (token) -> String in
var new = token
for (macro, repl) in macros {
new = new == macro ? repl : new
}
return new
})
if !handleGlobal(tokens: newTokens) {
return nil
}
} else {
updated += updatedLine
}
}
} else {
return nil
}
}
return updated
}
class func separateBySemiColons(text: String) -> [String] {
enum BracketScopes : String {
case curly = "{"
case string = "\""
case normal = ""
var closing : String {
switch self {
case .curly: return "}"
case .string: return "\""
case .normal: return ""
}
}
}
let scopeStack = XGStack<BracketScopes>()
let stack = text.stack
var currentToken = ""
var tokens = [String]()
scopeStack.push(.normal)
while !stack.isEmpty {
let current = stack.pop()
if (current == ";" && scopeStack.peek() != .string && scopeStack.peek() != .curly) {
tokens.append(currentToken)
currentToken = ""
} else if scopeStack.peek() == .string {
if current == "\"" {
scopeStack.popVoid()
}
currentToken += current
} else if let bracket = BracketScopes(rawValue: current) {
scopeStack.push(bracket)
currentToken += current
} else {
if current == "}" {
if scopeStack.peek() == .curly {
scopeStack.popVoid()
}
}
currentToken += current
}
}
if currentToken.length > 0 {
tokens.append(currentToken)
}
return tokens.filter({ (s) -> Bool in
return s.length > 0
})
}
class func evalStatementXDS(body: String) -> [XDSExpr]? {
var statements = [XDSExpr]()
let lines = separateBySemiColons(text: body)
for line in lines {
if let subTokens = tokeniseXDS(text: line) {
if let expr = evalTokensXDS(tokens: subTokens, subExpr: false) {
statements.append(expr)
} else {
// error in eval tokens
return nil
}
} else {
// error in tokenise
return nil
}
}
return statements
}
class func evalTokensXDS(tokens: [String], subExpr: Bool) -> XDSExpr? {
// the tokens are considered a "sub expression" if they are a part of a larger expression, the result of recursively evaluating tokens.
// this doesn't include if they are part of a compound statement
var tokens = tokens.filter { (s) -> Bool in
return s.length > 0
}
if tokens.count == 0 { return .nop }
if tokens.count == 1 {
let token = tokens[0]
// check for undefined macros
if token.substring(from: 0, to: 1) == "#" {
error = "Undefined macro: \(token)"
return nil
}
// accept bracketed expressions, function calls, location markers, return statements or any sub expression
if (token.contains("(") && token.contains(")")) || token.substring(from: 0, to: 1) == "@" || subExpr || token == "return" {
// return statement
if token == "return" {