-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
2267 lines (1808 loc) · 54.3 KB
/
main.go
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
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"reflect"
"strconv"
"strings"
"unicode"
//"time"
//"compiler/cmd"
)
const (
//errors
CMD_ARG_ERR string = "\u001B[91mINVALID COMMAND\u001B[0m\n"
METHOD_DECLARATION_ERR string = "The '{' token should not have any following token except new line feed or space"
INSUFFICIENT_VARS_ERR string = "the number of vars on the lhs dont match with the values on the rhs"
INSUFFICIENT_ARGS_FOR_INPUT_ERR string = "input statement should have 2 arguments (var,\"line\")\nthe line will br printed and \nvar will be assigned the value to"
MAIN_MISSING_ERR string = "FATAL ERROR\nMETHOD MAIN IS MISSING"
BUILD_FAIL_ERR string = "FATAL ERROR\nBUILD FAILED"
//files
DEFAULT_EXEC_FILE = "lethalityTest.mskt"
//for method syntactic sugar
METHOD_SYNTACTIC_SUGAR_STORAGE = "methodSugar.txt"
SUGAR_DELIM = "|"
//syntax
NORMAL_ASSIGNMENT string = "="
LEXICAL_VAR_SCOPE_ASIGNMENT string = ":= "
SYNTACTIC_ASSIGNMENT string = "<-"
COMMENT_START string = "#"
DECLARATION_DELIM string = " ... "
THREAD_ELEMENT_DELIM string = ";"
RETURN_STATEMENT string = "return "
METHOD_DECLARATION string = "func "
VAR_DECALRATION string = "var "
SCOPE_DECLARATION string = "scope "
PROCESS_DECLARATION string = "process "
THREAD_EXECUTION string = "run ... concurrently"
//special syntax
PRINTLN string = "println "
PRINT string = "print "
INPUT string = "input "
NOT string = "not "
IF string = "if "
IF_ARGS_ARE_EQUAL string = "are equal"
ELSE string = "else "
WHILE string = "while "
//special constants
NULL = "null"
//data types
NUMBER = "|int|"
STRING = "|str|"
BOOLEAN = "|charge|"
DOUBLE = "|double|"
SYSTEM_STRING = "|sys-str|"
)
//structs
type actionFunc func(string) (bool, string)
type oprAction func(Data, Data) (string, bool)
type CmdArgs struct {
action actionFunc
}
type Data struct {
value string
Type string
stringRep string
}
type MethodData struct {
parameters string
data Block
scopeNode ScopeNode
calledBy *MethodData
calledAt int
calledWith string
}
type ScopeNode struct {
parent *ScopeNode
varSave map[string]Data
presentLine int
owner *MethodData
}
type LoopData struct {
data MethodData
condition string
}
type VarSyntaxData struct {
data Block
}
type Block struct {
data []string
}
type Operators struct {
rep string
action oprAction
}
type Thread struct {
function string
name string
}
var threadSave map[string]Thread
//var processes map[string]Process
var varSyntaxSave map[string]VarSyntaxData
var varSyntaxNames []string
var methodSave map[string]*MethodData
var methodNames []string
var globalScope ScopeNode
//operators
var operatorList []Operators
var buldFailure bool
//execution tree
var executionListHeadNode *MethodData
func main() {
argHandler := InititializeCMD()
//this function is HUGE and is at the end
InititializeOperators()
args := getUserArgs()
if args != "shell" {
threadSave = make(map[string]Thread)
methodSave = make(map[string]*MethodData)
varSyntaxSave = make(map[string]VarSyntaxData)
globalScope = ScopeNode{nil, make(map[string]Data), 0, &MethodData{}}
program := Interpret(args, argHandler)
startExec(program)
} else {
fmt.Println("WELCOME TO VIPER LANG")
for true {
//process = make(map[string]Process)
threadSave = make(map[string]Thread)
methodSave = make(map[string]*MethodData)
varSyntaxSave = make(map[string]VarSyntaxData)
globalScope = ScopeNode{nil, make(map[string]Data), 0, &MethodData{}}
userInput := ""
reader := bufio.NewReader(os.Stdin)
fmt.Print("\u001B[92m> \u001B[0m")
userInput, _ = reader.ReadString('\n')
userInput = strings.Replace(userInput, "\n", "", -1)
program := Interpret(userInput, argHandler)
startExec(program)
nullifyData()
}
}
}
func nullifyData() {
threadSave = nil
varSyntaxSave = nil
methodSave = nil
globalScope = ScopeNode{}
methodNames = nil
varSyntaxNames = nil
buldFailure = false
}
//initializes the commands
func InititializeCMD() [3]CmdArgs {
var argHandler [3]CmdArgs
argHandler[0].action = func(args string) (bool, string) {
if strings.TrimSpace(args) == "run -d" {
str := CommenceReading(DEFAULT_EXEC_FILE)
return true, str
}
return false, ""
}
argHandler[1].action = func(args string) (bool, string) {
if strings.HasPrefix(args, "run ") {
parts := []rune(args)
fileName := string(parts[4:])
str := CommenceReading(fileName)
return true, str
}
return false, ""
}
argHandler[2].action = func(args string) (bool, string) {
if args == "quit" || args == "exit" {
os.Exit(0)
}
return false, ""
}
return argHandler
}
func err(args string) {
fmt.Println("\u001B[91m" + args + "\u001B[0m")
}
func getUserArgs() string {
if len(os.Args) == 1 {
return "shell"
}
str := ""
for i := 1; i < len(os.Args); i++ {
str = str + os.Args[i] + " "
}
return str
}
//reads the file
func CommenceReading(fileName string) string {
data, ERR := ioutil.ReadFile(fileName)
if ERR != nil {
fmt.Print("\u001B[91m", ERR, "\u001B[0m\n")
os.Exit(0)
return ""
}
fmt.Println("\u001B[92mFILE OPENED\u001B[0m\n")
program := string(data)
return program
}
//interprets whatever commans is given
func Interpret(input string, argHandler [3]CmdArgs) string {
for i := 0; i < len(argHandler); i++ {
success, data := argHandler[i].action(input)
if success {
return data
}
}
return CMD_ARG_ERR
}
//
func startExec(args string) {
if args == CMD_ARG_ERR {
fmt.Print(CMD_ARG_ERR)
} else {
AssignmentRun(args)
}
}
func AssignmentRun(program string) {
//the splitting on new line works
splitCode := strings.Split(program, "\n")
StaticallyInitialize(splitCode)
}
func StaticallyInitialize(program []string) {
for i := 0; i < len(program); i++ {
program[i] = strings.TrimSpace(program[i])
if strings.HasPrefix(program[i], COMMENT_START) {
program[i] = ""
continue
}
/*if AProcessIsBeingDeclared(program[i]) {
program = declareProcess(program,i)
}*/
if strings.HasPrefix(program[i], METHOD_DECLARATION) {
parts := []rune(program[i])
meth := string(parts[len(METHOD_DECLARATION):])
name, parameters := getNameAndParam(meth)
endIndex := globalScope.declareMethod(name, parameters, program, i)
program = deleteBlock(program, i, endIndex)
}
if varSyntaxIsDeclarable(program[i]) {
endIndex := declareVarSyntax(program, i)
program = deleteBlock(program, i, endIndex)
}
}
fmt.Println("\u001B[92mFIRST ASSIGNMENT RUN \nSTATUS: COMPLETE\u001B[0m\n")
StartExecution(program)
}
/*
func AProcessIsBeingDeclared (line string) (bool) {
return strings.HasPrefix(line,PROCESS_DECLARATION)
}
func declareProcess (program []string,index int) {
line := program[index]
name := strings.TrimSpace(string([]rune(line)[len(process):]))
name := strings.TrimSpace(string([]rune(name)[:len(name)-1]))
block,endIndex := getBlock(program,index,'{','}')
program = deleteBlock(program,index,endIndex)
process[name] = block
return program
}
*/
func getNameAndParam(meth string) (string, string) {
meth = strings.TrimSpace(meth)
parts := []rune(meth)
if !strings.HasSuffix(meth, "{") {
parts = append(parts, ' ')
}
parts[len(parts)-1] = ' '
for i := 0; i < len(parts); i++ {
if parts[i] == '(' {
name := string(parts[:i])
param := string(parts[i:])
return strings.TrimSpace(name), param
}
}
return strings.TrimSpace(string(parts)), ""
}
func (caller ScopeNode) declareMethod(name string, parameters string, program []string, index int) int {
elems := []rune(strings.TrimSpace(parameters))
var startIndex, endIndex int
var hasParam bool
for i := 0; i < len(elems); i++ {
if elems[i] == '(' {
hasParam = true
startIndex = i
continue
}
if elems[i] == ')' {
endIndex = i
break
}
}
param := ""
if hasParam {
param = string(elems[startIndex+1 : endIndex])
}
block, endIndex := getBlock(program, index, '{', '}')
node := MethodData{param, block, ScopeNode{&caller, make(map[string]Data), 0, &MethodData{}}, &MethodData{}, 0, ""}
methodSave[name] = &node
methodNames = append(methodNames, name)
return endIndex
}
func getBlock(program []string, startIndex int, start rune, end rune) (Block, int) {
num_of_nested_blocks := 0
endIndex := startIndex
for i := startIndex; i < len(program); i++ {
program[i] = strings.TrimSpace(program[i])
elems := []rune(program[i])
for j := 0; j < len(elems); j++ {
if elems[j] == '#' {
break
}
if elems[j] == start {
num_of_nested_blocks++
j = j + 1
continue
}
if elems[j] == end {
num_of_nested_blocks--
}
}
if num_of_nested_blocks == 0 {
endIndex = i
break
}
}
if startIndex == endIndex {
return Block{}, -1
}
snippet := make([]string, endIndex-startIndex)
for i := startIndex; i < endIndex; i++ {
snippet[i-startIndex] = program[i]
}
return Block{snippet}, endIndex
}
func varSyntaxIsDeclarable(args string) bool {
return strings.Contains(args, SYNTACTIC_ASSIGNMENT)
}
func declareVarSyntax(program []string, index int) int {
name := strings.TrimSpace(strings.Split(program[index], SYNTACTIC_ASSIGNMENT)[0])
dataBlock, endIndex := getBlock(program, index, '(', ')')
vsData := VarSyntaxData{dataBlock}
varSyntaxSave[name] = vsData
varSyntaxNames = append(varSyntaxNames, name)
return endIndex
}
func StartExecution(program []string) {
for i := 0; i < len(methodNames); i++ {
param := methodSave[methodNames[i]].parameters
data := methodSave[methodNames[i]].data.data
scopeNode := methodSave[methodNames[i]].scopeNode
methodSave[methodNames[i]] = &MethodData{param, Block{replaceSpecialSyntax(data)}, scopeNode, &MethodData{}, 0, ""}
fmt.Println("\u001B[92mVAR SYNTAX REPLACEMENT IN METHOD [", methodNames[i], "] \nSTATUS: COMPLETE\u001B[0m\n")
}
err := callFunctionMAIN()
if err != "" {
autoCreateFunctionMAIN(program)
}
}
func replaceSpecialSyntax(program []string) []string {
for j := 0; j < len(varSyntaxNames); j++ {
name := varSyntaxNames[j]
value := varSyntaxSave[name].data.data
program = Insert(program, name, value)
}
return program
}
func Insert(program []string, name string, value []string) []string {
emptyArray := make([]string, len(value))
for i := 0; i < len(program); i++ {
if (strings.TrimSpace(program[i])) == name {
program[i] = ""
for k := 0; k < len(emptyArray); k++ {
program = append(program, emptyArray[k])
}
program = moveRight(program, i, len(value))
for k := 1; k < len(value); k++ {
program[i+k] = value[k]
}
}
}
return program
}
func moveRight(program []string, index int, times int) []string {
output := make([]string, len(program)-times)
for i := 1; i < index; i++ {
output[i] = program[i]
}
for i := len(program) - 1; i > times; i-- {
output = append(output, program[i])
}
return output
}
func callFunctionMAIN() string {
fmt.Println("\u001B[92mEXECUTION ENVIRONMENT SET\nCODE EXECUTION STARTING\u001B[0m\n\n")
main := methodSave["main"]
if methodSave["main"] == nil {
return MAIN_MISSING_ERR
}
data := MethodData{main.parameters, main.data, main.scopeNode, &MethodData{}, 0, ""}
data.runThrough(0)
return ""
}
func autoCreateFunctionMAIN(program []string) {
main := MethodData{"", Block{program}, ScopeNode{&globalScope, make(map[string]Data), 0, &MethodData{}}, &MethodData{}, 0, ""}
main.data.data = replaceSpecialSyntax(main.data.data)
methodSave["main"] = &main
callFunctionMAIN()
}
func (data MethodData) runThroughFnc(index int, scpNode ScopeNode) {
parts := strings.Split(strings.TrimSpace(data.data.data[0]), "=")
lhs := strings.Split(parts[0], ",")
rhs := strings.Split(parts[1], ",")
if len(lhs) != len(rhs) {
err("insufficient parameters to call function")
}
for i := 0; i < len(lhs); i++ {
lhs[i], rhs[i] = strings.TrimSpace(lhs[i]), strings.TrimSpace(rhs[i])
var_data := scpNode.compute(rhs[i])
data.scopeNode.varSave[lhs[i]] = var_data
}
data.runThrough(1)
}
func (data MethodData) runThrough(index int) {
program := data.data.data
data.scopeNode.owner = &data
for i := index; i < len(program); i++ {
//fmt.Println(program)
data.scopeNode.presentLine = i
program[i] = strings.TrimSpace(program[i])
done, _ := data.scopeNode.checkSpecialFunctions(program[i])
if done {
//i = i + increment
continue
}
if lexScopingIsBeingRequested(program[i]) {
data.scopeNode.lexScopingAssign(program[i])
continue
}
if threadExecution(program[i]) {
data.scopeNode.runThread(program[i])
}
if assignable(program[i]) {
data.scopeNode.assign(program[i])
continue
}
if varSyntaxIsDeclarable(program[i]) {
endIndex := declareVarSyntax(program, i)
program = deleteBlock(program, i, endIndex)
}
if strings.HasPrefix(program[i], "{") && strings.HasSuffix(program[i], "}") {
str := string([]rune(program[i])[1 : len(program[i])-1])
val, found := data.scopeNode.searchTreeFor(str)
value := val.value
if found {
program[i] = value
i = i - 1
continue
}
}
funcCall, methodName := functionCall(program[i])
if funcCall {
data.scopeNode.callFunction(program[i], methodName, data, i)
continue
}
if strings.HasPrefix(program[i], RETURN_STATEMENT) {
data.functionReturn(program[i])
continue
}
}
data = MethodData{}
}
func assignable(line string) bool {
return strings.Contains(line, NORMAL_ASSIGNMENT)
}
func (caller ScopeNode) assign(args string) {
if strings.HasPrefix(args, VAR_DECALRATION) {
args = strings.TrimSpace(string([]rune(args)[len(VAR_DECALRATION):]))
} else {
args = strings.TrimSpace(args)
}
tempParts := strings.Split(args, NORMAL_ASSIGNMENT)
lhs := strings.Split(strings.TrimSpace(tempParts[0]), ",")
rhs := strings.Split(strings.TrimSpace(tempParts[1]), ",")
caller.assignValues(lhs, rhs, false)
}
func lexScopingIsBeingRequested(line string) bool {
return strings.Contains(line, LEXICAL_VAR_SCOPE_ASIGNMENT)
}
func (caller ScopeNode) lexScopingAssign(args string) {
if strings.HasPrefix(args, LEXICAL_VAR_SCOPE_ASIGNMENT) {
args = strings.TrimSpace(string([]rune(args)[len(LEXICAL_VAR_SCOPE_ASIGNMENT):]))
} else {
args = strings.TrimSpace(args)
}
tempParts := strings.Split(args, LEXICAL_VAR_SCOPE_ASIGNMENT)
lhs := strings.Split(strings.TrimSpace(tempParts[0]), ",")
rhs := strings.Split(strings.TrimSpace(tempParts[1]), ",")
caller.assignValues(lhs, rhs, true)
}
func threadExecution(line string) bool {
parts := strings.Split(THREAD_EXECUTION, DECLARATION_DELIM)
condition1 := strings.HasPrefix(line, parts[0])
condition2 := strings.HasSuffix(line, parts[1])
return condition1 && condition2
}
func (caller ScopeNode) runThread(line string) {
parts := strings.Split(THREAD_EXECUTION, DECLARATION_DELIM)
name := string([]rune(line)[len(parts[0]) : len(line)-len(parts[1])])
name = strings.TrimSpace(name)
name = removeIfPresent(name, "[", "]")
elems := strings.Split(name, THREAD_ELEMENT_DELIM)
thisThread := Thread{}
for i := 0; i < len(elems); i++ {
elems[i] = strings.TrimSpace(elems[i])
switch i {
case 0:
thisThread.function = elems[0]
case 1:
if decipherType(elems[1]) == NUMBER {
//thisThread.priority,_ = strconv.Atoi(elems[1])
} else {
thisThread.name = elems[1]
}
case 2:
if decipherType(elems[2]) == NUMBER {
//thisThread.priority,_ = strconv.Atoi(elems[2])
} else {
thisThread.name = elems[2]
}
default:
err("Too many arguments to call a thread")
}
}
if thisThread.name != "" {
threadSave[thisThread.name] = thisThread
}
itIs, name := functionCall(thisThread.function)
if !itIs {
err("the function called in the thread does not exist")
}
go caller.callFunction(thisThread.function, name, *(caller.owner), caller.presentLine)
}
func (caller ScopeNode) assignValues(names, values []string, lexScoping bool) {
for i := 0; i < len(values); i++ {
names[i] = strings.TrimSpace(names[i])
val := caller.compute(values[i])
if lexScoping {
fmt.Println("lex")
caller.varSave[names[i]] = val
} else {
caller.searchTheTreeAndPlace(names[i], val)
}
}
}
func (caller ScopeNode) searchTheTreeAndPlace(name string, value Data) {
presentNode := &caller
successFullNode := &caller
for !reflect.DeepEqual(presentNode.owner, &MethodData{}) {
if (presentNode.varSave[name] != Data{}) {
successFullNode = presentNode
}
presentNode = presentNode.parent
}
successFullNode.varSave[name] = value
}
func deleteBlock(program []string, startIndex int, endIndex int) []string {
for i := startIndex; i <= endIndex; i++ {
program[i] = ""
}
return program
}
func functionCall(args string) (bool, string) {
for i := 0; i < len(methodNames); i++ {
if strings.HasPrefix(args, methodNames[i]) {
return true, methodNames[i]
}
}
return false, ""
}
func (caller ScopeNode) callFunction(method string, name string, calledBy MethodData, callingAt int) {
methodSave[name].calledAt = callingAt
methodSave[name].calledBy = &calledBy
methodSave[name].calledWith = method
method = removeSyntacticSugar(strings.TrimSpace(method))
param := string([]rune(method)[len(name)+1:])
assignmentString := methodSave[name].parameters + " = " + param
methodSave[name].data.data[0] = assignmentString
methodSave[name].runThroughFnc(0, caller)
}
func removeSyntacticSugar(method string) string {
data, ERR := ioutil.ReadFile(METHOD_SYNTACTIC_SUGAR_STORAGE)
if ERR != nil {
fmt.Print("\u001B[91m", ERR, "\u001B[0m\n")
os.Exit(0)
return ""
}
allSugar := strings.Split(string(data), "\n")
methArray := strings.Split(method, " ")
returnArray := make([]string, len(methArray))
for i := 0; i < len(allSugar); i++ {
sugar := strings.Split(allSugar[i], SUGAR_DELIM)
for j := 0; j < len(returnArray); j++ {
for k := 0; k < len(sugar); k++ {
returnArray[j] = methArray[j]
if strings.TrimSpace(methArray[j]) == sugar[k] {
returnArray[j] = sugar[1]
break
}
}
}
}
returnString := ""
for i := 0; i < len(returnArray); i++ {
returnString = returnString + returnArray[i] + " "
}
return returnString
}
func (caller ScopeNode) checkSpecialFunctions(line string) (bool, int) {
if strings.HasPrefix(line, PRINTLN) {
caller.println(line)
return true, 0
}
if strings.HasPrefix(line, PRINT) {
caller.print(line)
return true, 0
}
if strings.HasPrefix(line, INPUT) {
caller.takeInput(line)
return true, 0
}
if strings.HasPrefix(line, NOT) {
caller.NOT(line)
return true, 0
}
if strings.HasPrefix(line, IF) {
caller.tryIf(line)
return true, 1
}
if strings.HasPrefix(line, WHILE) {
caller.tryWhile(line)
return true, 1
}
return false, 0
}
func (caller ScopeNode) println(statement string) {
statement = strings.TrimSpace(statement)
statement = string([]rune(statement)[len(PRINTLN):])
if strings.HasPrefix(statement, "\"") && strings.HasSuffix(statement, "\"") || strings.HasPrefix(statement, "'") && strings.HasSuffix(statement, "'") {
statement = string([]rune(statement)[1 : len(statement)-1])
statement = caller.replaceVars(statement)
} else {
statement = caller.compute(statement).stringRep
}
fmt.Println("\u001B[96m" + statement + "\u001B[0m")
}
func (caller ScopeNode) print(statement string) {
statement = strings.TrimSpace(statement)
statement = string([]rune(statement)[len(PRINT):])
if strings.HasPrefix(statement, "\"") && strings.HasSuffix(statement, "\"") || strings.HasPrefix(statement, "'") && strings.HasSuffix(statement, "'") {
statement = string([]rune(statement)[1 : len(statement)-1])
statement = caller.replaceVars(statement)
} else {
statement = caller.compute(statement).stringRep
}
fmt.Print("\u001B[96m" + statement + "\u001B[0m")
}
func (caller ScopeNode) replaceVars(statement string) string {
chars := []rune(" " + statement)
var name []rune
var appendable bool
var startIndex, endIndex int
for i := 0; i < len(chars); i++ {
if appendable {
name = append(name, chars[i])
}
if chars[i] == '{' {
appendable = true
startIndex = i
}
if chars[i] == '}' {
appendable = false
endIndex = i + 1
varName := string(chars[startIndex:endIndex])
pureName := string([]rune(varName)[1 : len(varName)-1])
value, found := caller.searchTreeFor(pureName)
if found {
statement = strings.Replace(statement, varName, value.stringRep, 1)
} else {
statement = strings.Replace(statement, varName, NULL, 1)
}
name = make([]rune, 0)
}
}
return statement
}
func (caller ScopeNode) searchTreeFor(name string) (Data, bool) {
presentNode := &caller
for !reflect.DeepEqual(presentNode.owner, &MethodData{}) {
if !reflect.DeepEqual(presentNode.varSave[name], Data{}) {
return presentNode.varSave[name], true
}
presentNode = presentNode.parent
}
return Data{}, false
}
func (caller ScopeNode) takeInput(line string) {
line = strings.TrimSpace(line)
line = string([]rune(line)[len(INPUT) : len(line)-1])
parts := strings.Split(line, ",")
if len(parts) < 2 || len(parts) > 2 {
fmt.Println("\u001B[91m"+INSUFFICIENT_ARGS_FOR_INPUT_ERR, "\u001B[0m\n")
os.Exit(0)
}
parts[0] = strings.TrimSpace(parts[0])
parts[1] = string([]rune(parts[1])[1:])
caller.print(PRINT + " " + parts[1] + "\"")
reader := bufio.NewReader(os.Stdin)
str, _ := reader.ReadString('\n')
nstr := "\"" + string([]rune(str)[:len(str)-1]) + "\""
data := encapsulate(nstr)
caller.searchTheTreeAndPlace(parts[0], data)
}
func (caller ScopeNode) NOT(line string) {
line = strings.TrimSpace(line)
line = string([]rune(line)[len(NOT):])
parts := strings.Split(line, ",")
name := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
val, found := caller.searchTreeFor(value)
if found {
value = val.value
}
fmt.Println("|" + value + "|")
boolCounterpart, _ := strconv.ParseBool(value)
boolVal := !boolCounterpart
value = strconv.FormatBool(boolVal)
var data Data = encapsulate(value)
caller.varSave[name] = data
}
func (caller ScopeNode) tryIf(line string) {
ogLine := line
line = string([]rune(line)[len(IF):])
line = strings.TrimSpace(line)
if !strings.HasSuffix(line, "{") {
err("if block should always end with \"{\"")
os.Exit(0)
}
line = strings.TrimSpace(string([]rune(line)[:len(line)-1]))
line = caller.computeBooleanCondition(line)
data := caller.owner.data.data
index := caller.presentLine
//declaring if block
if_dataBlock, ifEndIndex := getBlock(data, index, '{', '}')
scpNode := ScopeNode{&caller, make(map[string]Data), 0, &MethodData{}}
ifBlock := MethodData{"", if_dataBlock, scpNode, caller.owner, scpNode.presentLine, ogLine}
//declaring else block
else_dataBlock, elseEndIndex := getBlock(data, ifEndIndex+1, '{', '}')
scpNode = ScopeNode{&caller, make(map[string]Data), 0, &MethodData{}}
elseBlock := MethodData{"", else_dataBlock, scpNode, caller.owner, scpNode.presentLine + ifEndIndex, ogLine}
if line == "true" {
ifBlock.runThrough(1)
if elseEndIndex == -1 {
if strings.HasPrefix(ifBlock.calledBy.data.data[0], WHILE) {
mData := *(caller.owner)
prevCallIndex := mData.calledBy.scopeNode.presentLine
line := mData.data.data[0]
line = string([]rune(line)[len(WHILE):])
line = strings.TrimSpace(line)
line = strings.TrimSpace(string([]rune(line)[:len(line)-1]))
condition := line
caller.owner.calledBy.scopeNode.loop(mData, ifEndIndex, prevCallIndex+len(mData.data.data), condition)
} else {
caller.owner.runThrough(ifEndIndex)
os.Exit(0)
}
} else {
if strings.HasPrefix(ifBlock.calledBy.data.data[0], WHILE) {
caller.CallerIsWhile(elseEndIndex)
} else {
caller.owner.runThrough(elseEndIndex)
os.Exit(0)
}
}