summaryrefslogtreecommitdiff
path: root/henshin
blob: 9b1c4fdf2e722eaf0363ff2b26d0fc54e71b0325 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
#!/bin/env python3


import sys
import argparse
import logging
import ply.lex as lex
import ply.yacc as yacc
from enum import Enum
import collections.abc
import os



# args

parser = argparse.ArgumentParser(
    prog='henshin'
)

parser.add_argument('filename')

parser.add_argument(
    '--lex',
    default=False,
    action=argparse.BooleanOptionalAction,
)

parser.add_argument(
    '--debug',
    default=False,
    action=argparse.BooleanOptionalAction,
)

args = parser.parse_args()


input = open(args.filename).read()



# log

logging.basicConfig(
    level = logging.DEBUG,
    filename = "parselog.txt",
    filemode = "w",
)

log = logging.getLogger()






# Lexer

reserved = {
    "function": "FUNCTION",
    "if": "IF",
    "else": "ELSE",
    "return": "RETURN",
    "const": "CONST",
    "var": "VAR",


    "integer": "TYPE_INTEGER",
    "string": "TYPE_STRING",
    "void": "TYPE_VOID",
    "type": "TYPE_TYPE",

    "and": "AND",
    "or": "OR",
    "not": "NOT",
}

tokens = [
    "OPERATOR_PLUS",
    "OPERATOR_MINUS",
    "OPERATOR_MULTIPLY",
    "OPERATOR_DIVIDE",
    "ASSIGN",

    "OPERATOR_PIPE",
    "OPERATOR_PIPE_REPLACEMENT",

    "COMPARE_EQUAL",
    "COMPARE_NOT_EQUAL",
    "COMPARE_GREATER",
    "COMPARE_LESSER",
    "COMPARE_GREATER_EQUAL",
    "COMPARE_LESSER_EQUAL",


    "PARENTHESIS_LEFT",
    "PARENTHESIS_RIGHT",
    "BRACE_LEFT",
    "BRACE_RIGHT",
    "BRACKET_LEFT",
    "BRACKET_RIGHT",
    "PIPE",


    "NAMESPACE_ACCESSOR",


    "COMMA",
    "COLON",


    "IDENTIFIER",
    "NUMBER",
    "STRING",
    "COMMENT",
] + list(reserved.values())



t_OPERATOR_PLUS = r'\+'
t_OPERATOR_MINUS = r'-'
t_OPERATOR_MULTIPLY = r'\*'
t_OPERATOR_DIVIDE = r'/'
t_ASSIGN = r'='

t_OPERATOR_PIPE = r'=>'
t_OPERATOR_PIPE_REPLACEMENT = r'\$'

t_COMPARE_EQUAL = r'=='
t_COMPARE_NOT_EQUAL = r'!='
t_COMPARE_GREATER = r'>'
t_COMPARE_LESSER = r'<'
t_COMPARE_GREATER_EQUAL = r'>='
t_COMPARE_LESSER_EQUAL = r'<='


t_PARENTHESIS_LEFT = r'\('
t_PARENTHESIS_RIGHT = r'\)'
t_BRACKET_LEFT = r'\['
t_BRACKET_RIGHT = r'\]'
t_BRACE_LEFT = r'{'
t_BRACE_RIGHT = r'}'
t_PIPE = r'\|'


t_NAMESPACE_ACCESSOR = r'\.'


t_COMMA = r','
t_COLON = r':'



def t_IDENTIFIER(t):
    r'[a-zA-Z][a-zA-Z0-9_]*'

    t.type = reserved.get(t.value, 'IDENTIFIER')

    return t

def t_NUMBER(t):
    r'[0-9]+'

    t.value = int(t.value)

    return t

def t_STRING(t):
    r'(".*?")'

    t.value = t.value.replace('"', '')

    return t

def t_COMMENT(t):
    r'//.*'

    pass


def t_newline(t):
    r'\n+'

    t.lexer.lineno += len(t.value)

t_ignore = ' \t'


def t_error(t):
    print("undefined: '%s'" % t.value[0])
    t.lexer.skip(1)


lexer = lex.lex(debug=True, debuglog=log)

if args.debug and args.lex:
    lexer.input(input)

    lineno = 0
    for token in lexer:
        if token.lineno != lineno:
            lineno = token.lineno
            print("\nLine %s:" % token.lineno)

        print('%s: "%s" --' % (token.type, token.value), end=' ')
        # print(token.value, end=' ')
    print("\n")






# Parser

class AstNodeExpressionType(Enum):
    IDENTIFIER = 'identifier'
    NUMBER = 'number'
    STRING = 'string'
    ARRAY = 'array'
    MAP = 'map'

class AstNodeComparatorType(Enum):
    EQUAL = "=="
    NOT_EQUAL = "!="
    GREATER = ">"
    LESSER = "<"
    GREATER_EQUAL = ">="
    LESSER_EQUAL = "<="

class AstNode: pass

class AstNodeVariableDeclarationStatement(AstNode):
    def __init__(self, type, name, variable_type, value):
        self.type = type
        self.name = name
        self.variable_type = variable_type
        self.value = value

class AstNodeVariableReassignmentStatement(AstNode):
    def __init__(self, name, value):
        self.name = name
        self.value = value

class AstNodeVariableTypes(AstNode):
    def __init__(self, operator, left, right):
        self.operator = operator
        self.left = left
        self.right = right

class AstNodeVariableTypeArray(AstNode):
    def __init__(self, type):
        self.type = type

class AstNodeVariableTypeMap(AstNode):
    def __init__(self, key_type, value_type):
        self.key_type = key_type
        self.value_type = value_type

class AstNodeVariableTypeType(AstNode):
    def __init__(self, base_type):
        self.base_type = base_type

class AstNodeMapElement(AstNode):
    def __init__(self, key, value):
        self.key = key
        self.value = value

class AstNodeExpression(AstNode):
    def __init__(self, type, value):
        self.type = type
        self.value = value

class AstNodeOperatorExpression(AstNode):
    def __init__(self, type, left, right):
        self.type = type
        self.left = left
        self.right = right

class AstNodeFunctionDeclaration(AstNode):
    def __init__(self, parameters, return_type, body):
        self.parameters = parameters
        self.return_type = return_type
        self.body = body

class AstNodeFunctionDeclarationParameter(AstNode):
    def __init__(self, name, type):
        self.name = name
        self.type = type

class AstNodeReturnStatement(AstNode):
    def __init__(self, expression):
        self.expression = expression

class AstNodeFunctionCall(AstNode):
    def __init__(self, name, parameters):
        self.name = name
        self.parameters = parameters

class AstNodeFunctionCallParameter(AstNode):
    def __init__(self, name, value):
        self.name = name
        self.value = value

class AstNodePipe(AstNode):
    def __init__(self, left, right):
        self.left = left
        self.right = right

class AstNodeTypeDeclaration(AstNode):
    def __init__(self, body):
        self.body = body

class AstNodeNamespaceAccess(AstNode):
    def __init__(self, left, right):
        self.left = left
        self.right = right

class AstNodeIf(AstNode):
    def __init__(self, arms):
        self.arms = arms

class AstNodeIfArm(AstNode):
    def __init__(self, comparison, body):
        self.comparison = comparison
        self.body = body

class AstNodeCompare(AstNode):
    def __init__(self, left, comparator, right):
        self.left = left
        self.comparator = comparator
        self.right = right

class AstNodeCompareExpressions(AstNode):
    def __init__(self, operator, left, right):
        self.operator = operator
        self.left = left
        self.right = right


precedence = (
    ('left', 'OPERATOR_PLUS', 'OPERATOR_MINUS'),
    ('left', 'OPERATOR_MULTIPLY', 'OPERATOR_DIVIDE'),
    ('left', 'OR', 'OR'),
    ('left', 'AND', 'AND'),
)



def p_program(p):
    '''program : program_statement
               | program_statement program'''

    def resolve_nodes(node, level):
        node_dict = node.__dict__
        for property in node_dict:
            node_value = node_dict[property]

            if isinstance(node_value, AstNode):
                print('> '*level, property, node_value.__class__.__name__)
                resolve_nodes(node_value, level+1)
            elif isinstance(node_value, list):
                list_length = len(node_value)
                print('> '*level, property + '[' + str(list_length) + ']:')

                if list_length == 0:
                    print('> '*(level+1), 'None')
                else:
                    for idx in range(list_length):
                        item = node_value[idx]

                        print('> '*(level+1), str(idx+1)+'.', item.__class__.__name__)
                        resolve_nodes(item, level+2)
            else:
                print('> '*level, property, node_dict[property])

    if args.debug and p[1]:
        print(p[1].__class__.__name__)
        resolve_nodes(p[1], 0)

    program = [p[1]]
    if len(p) > 2:
        program.extend(p[2])
    p[0] = program

def p_program_statement(p):
    '''program_statement : variable_declaration_statement
                         | variable_reassignment_statement
                         | function_call
                         | pipe
                         | if_statement'''

    p[0] = p[1]


def p_statements(p):
    '''statements : statement
                  | statement statements'''

    statements = [p[1]]
    if len(p) > 2:
        statements.extend(p[2])
    p[0] = statements


def p_statement(p):
    '''statement : variable_declaration_statement
                 | variable_reassignment_statement
                 | function_declaration
                 | function_call
                 | type_declaration
                 | pipe
                 | return_statement
                 | if_statement'''

    p[0] = p[1]




def p_function_declaration(p):
    '''function_declaration : PARENTHESIS_LEFT function_declaration_parameters PARENTHESIS_RIGHT COLON return_type BRACE_LEFT statements BRACE_RIGHT'''

    p[0] = AstNodeFunctionDeclaration(p[2], p[5], p[7])


def p_function_declaration_parameters(p):
    '''function_declaration_parameters : function_declaration_parameter COMMA function_declaration_parameters
                                       | function_declaration_parameter COMMA
                                       | function_declaration_parameter
                                       |'''

    parameters = []
    if len(p) == 2:
        parameters.append(p[1])
    if len(p) == 4:
        parameters.extend(p[3])

    p[0] = parameters


def p_function_declaration_parameter(p):
    '''function_declaration_parameter : IDENTIFIER COLON variable_types'''

    p[0] = AstNodeFunctionDeclarationParameter(p[1], p[3])




def p_function_call(p):
    '''function_call : IDENTIFIER PARENTHESIS_LEFT function_call_parameters PARENTHESIS_RIGHT
                     | namespace_access PARENTHESIS_LEFT function_call_parameters PARENTHESIS_RIGHT'''

    p[0] = AstNodeFunctionCall(p[1], p[3])


def p_function_call_parameters(p):
    '''function_call_parameters : function_call_parameter COMMA function_call_parameters
                                | function_call_parameter COMMA
                                | function_call_parameter
                                |'''

    parameters = []
    if len(p) == 2:
        parameters.append(p[1])
    if len(p) == 4:
        parameters.extend(p[3])

    p[0] = parameters


def p_function_call_parameter(p):
    '''function_call_parameter : IDENTIFIER ASSIGN expression
                               | expression
                               | OPERATOR_PIPE_REPLACEMENT'''

    if len(p) == 4:
        p[0] = AstNodeFunctionCallParameter(p[1], p[3])
    else:
        p[0] = AstNodeFunctionCallParameter("", p[1])




def p_pipe(p):
    '''pipe : expression OPERATOR_PIPE pipe
            | expression OPERATOR_PIPE function_call'''

    p[0] = AstNodePipe(p[1], p[3])




def p_variable_declaration_statement(p):
    '''variable_declaration_statement : variable_declarator IDENTIFIER COLON variable_type ASSIGN expression'''

    p[0] = AstNodeVariableDeclarationStatement(p[1], p[2], p[4], p[6])


def p_variable_reassignment_statement(p): # TODO: adjust for object parameter assignment
    '''variable_reassignment_statement : IDENTIFIER ASSIGN expression
                                       | namespace_access ASSIGN expression'''

    p[0] = AstNodeVariableReassignmentStatement(p[1], p[3])


def p_variable_declarator(p):
    '''variable_declarator : CONST
                           | VAR'''
    p[0] = p[1]


def p_variable_type_primitive(p):
    '''variable_type_primitive : TYPE_INTEGER
                               | TYPE_STRING'''
    p[0] = p[1]

def p_variable_types_primitive(p):
    '''variable_types_primitive : variable_type_primitive AND variable_types_primitive
                                | variable_type_primitive OR variable_types_primitive
                                | variable_type_primitive'''

    if len(p) == 4:
        p[0] = AstNodeVariableTypes(p[2], p[1], p[3])
    else:
        p[0] = p[1]


def p_variable_type(p):
    '''variable_type : variable_type_array
                     | variable_type_map
                     | variable_type_type
                     | variable_type_primitive
                     | identifier
                     | TYPE_TYPE
                     | FUNCTION'''
    p[0] = p[1]


def p_variable_types(p):
    '''variable_types : variable_type AND variable_types
                      | variable_type OR variable_types
                      | variable_type'''

    if len(p) == 4:
        p[0] = AstNodeVariableTypes(p[2], p[1], p[3])
    else:
        p[0] = p[1]


def p_variable_type_array(p):
    '''variable_type_array : BRACKET_LEFT variable_types BRACKET_RIGHT'''

    p[0] = AstNodeVariableTypeArray(p[2])


def p_variable_type_map(p):
    '''variable_type_map : BRACKET_LEFT variable_types BRACKET_RIGHT BRACKET_LEFT variable_types BRACKET_RIGHT'''

    p[0] = AstNodeVariableTypeMap(p[2], p[5])

def p_variable_type_type(p):
    '''variable_type_type : TYPE_TYPE BRACKET_LEFT variable_type BRACKET_RIGHT'''

    p[0] = AstNodeVariableTypeType(p[3])



def p_return_statement(p):
    '''return_statement : RETURN expression'''

    p[0] = AstNodeReturnStatement(p[2])


def p_return_type(p):
    '''return_type : variable_type
                   | TYPE_VOID'''
    p[0] = p[1]



def p_type_declaration(p):
    '''type_declaration : BRACE_LEFT type_body BRACE_RIGHT'''

    p[0] = AstNodeTypeDeclaration(p[2])

def p_type_body(p):
    '''type_body : variable_declaration_statement
                 | variable_declaration_statement type_body'''

    type_body = [p[1]]
    if len(p) > 2:
        type_body.extend(p[2])
    p[0] = type_body



def p_identifier(p):
    '''identifier : IDENTIFIER'''

    p[0] = AstNodeExpression(AstNodeExpressionType.IDENTIFIER, p[1])


def p_number(p):
    '''number : NUMBER'''

    p[0] = AstNodeExpression(AstNodeExpressionType.NUMBER, p[1])


def p_string(p):
    '''string : STRING'''

    p[0] = AstNodeExpression(AstNodeExpressionType.STRING, p[1])


def p_array(p):
    '''array : BRACKET_LEFT array_elements BRACKET_RIGHT'''

    p[0] = AstNodeExpression(AstNodeExpressionType.ARRAY, p[2])


def p_array_elements(p):
    '''array_elements : array_element COMMA array_elements
                      | array_element COMMA
                      | array_element'''

    elements = [p[1]]
    if len(p) == 4:
        elements.extend(p[3])

    p[0] = elements


def p_array_element(p):
    '''array_element : expression'''

    p[0] = p[1]


def p_map(p):
    '''map : BRACKET_LEFT map_elements BRACKET_RIGHT'''

    p[0] = AstNodeExpression(AstNodeExpressionType.MAP, p[2])


def p_map_elements(p):
    '''map_elements : map_element COMMA map_elements
                    | map_element COMMA
                    | map_element'''

    elements = [p[1]]
    if len(p) == 4:
        elements.extend(p[3])

    p[0] = elements


def p_map_element(p):
    '''map_element : map_element_key ASSIGN expression'''

    p[0] = AstNodeMapElement(p[1], p[3])

def p_map_element_key(p):
    '''map_element_key : identifier
                       | number
                       | string'''

    p[0] = p[1]


def p_namespace_access(p):
    '''namespace_access : identifier NAMESPACE_ACCESSOR identifier
                        | namespace_access NAMESPACE_ACCESSOR identifier'''

    p[0] = AstNodeNamespaceAccess(p[1], p[3])


def p_if_statement(p):
    '''if_statement : if_arm ELSE if_statement
                    | if_arm'''

    arms = [p[1]]
    if len(p) == 4:
        arms.extend(p[3].arms)

    p[0] = AstNodeIf(arms)

def p_if_arm(p):
    '''if_arm : IF PARENTHESIS_LEFT compare_expressions PARENTHESIS_RIGHT BRACE_LEFT statements BRACE_RIGHT'''

    p[0] = AstNodeIfArm(p[3], p[6])

def p_compare_expression(p):
    '''compare_expression : expression comparator expression'''

    p[0] = AstNodeCompare(p[1], p[2], p[3])

def p_compare_expressions(p):
    '''compare_expressions : compare_expression AND compare_expressions
                           | compare_expression OR compare_expressions
                           | compare_expression'''

    if len(p) == 4:
        p[0] = AstNodeCompareExpressions(p[2], p[1], p[3])
    else:
        p[0] = p[1]

def p_comparator(p):
    '''comparator : COMPARE_EQUAL
                  | COMPARE_NOT_EQUAL
                  | COMPARE_GREATER
                  | COMPARE_LESSER
                  | COMPARE_GREATER_EQUAL
                  | COMPARE_LESSER_EQUAL'''

    # p[0] = AstNodeComparator(AstNodeComparatorType)
    p[0] = p[1]


def p_expression(p):
    '''expression : identifier
                  | number
                  | string
                  | array
                  | map
                  | function_declaration
                  | function_call
                  | type_declaration
                  | variable_type
                  | namespace_access
                  | compare_expressions
                  | expression OPERATOR_PLUS expression
                  | expression OPERATOR_MINUS expression
                  | expression OPERATOR_MULTIPLY expression
                  | expression OPERATOR_DIVIDE expression'''

    if len(p) == 4:
        p[0] = AstNodeOperatorExpression(p[2], p[1], p[3])
    else:
        p[0] = p[1]




def p_error(p):
    if p:
        line_start_column = input.rfind('\n', 0, p.lexpos) + 1
        column = (p.lexpos - line_start_column) + 1
        print("Syntax error in input! Line: {line}, Column: {column}".format(line=p.lineno, column=column), p)
    else:
        print("Unknown Error :(")




parser = yacc.yacc(debug=True, debuglog=log)
result = parser.parse(input)


def function_import(file_path):
    return interpret(
        parser.parse(
            open(os.path.dirname(args.filename) + "/" + file_path).read()
        ),
        variables.copy()
    )

variables = {
    "print": print,
    "import": function_import,
}
types = {}


def is_statement(statement):
    return (
        type(statement) is AstNodeVariableDeclarationStatement or
        type(statement) is AstNodeVariableReassignmentStatement or
        type(statement) is AstNodeFunctionCall or
        type(statement) is AstNodePipe
    )


def to_parameters_dict(parameters, context):
    dictionary = {}

    for idx, parameter in enumerate(parameters):
        if type(parameter) is AstNodeFunctionDeclarationParameter:
            dictionary[parameter.name] = None
        elif type(parameter) is AstNodeFunctionCallParameter:
            value = parameter.value

            if value == "$":
                value = context["$"]

            if parameter.name == "":
                dictionary[idx] = value
            else:
                dictionary[parameter.name] = value

    return dictionary


def merge_dict(dict1, dict2):
    for key, val in dict1.items():
        if type(val) == dict:
            if key in dict2 and type(dict2[key] == dict):
                merge_dict(dict1[key], dict2[key])
        else:
            if key in dict2:
                dict1[key] = dict2[key]

    for key, val in dict2.items():
        if not key in dict1:
            dict1[key] = val

    return dict1

def nested_set(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value

def update(d, u):
    for k, v in u.items():
        if isinstance(v, collections.abc.Mapping):
            d[k] = update(d.get(k, {}), v)
        else:
            d[k] = v
    return d


def get_namespace_path(namespace, context):
    path = []

    left = evaluate_expression(namespace.left, context | {"NAMESPACE_ACCESS": True})
    right = evaluate_expression(namespace.right, context | {"NAMESPACE_ACCESS": True})

    if type(left) is list:
        path.extend(left)
    else:
        path.append(left)

    path.append(right)

    return path


def evaluate_statement(statement, context):
    scoped_variables = {}

    # variable declaration
    if type(statement) is AstNodeVariableDeclarationStatement:
        value = evaluate_expression(statement.value, context)
        scoped_variables[statement.name] = value
        types[statement.name] = statement.variable_type

    # variable reassignment
    elif type(statement) is AstNodeVariableReassignmentStatement:
        value = evaluate_expression(statement.value, context)
        name = statement.name

        if type(name) is AstNodeNamespaceAccess:
            namespace_path = get_namespace_path(name, context)

            nested_update = {}
            nested_set(nested_update, namespace_path, value)
            scoped_variables = update(context, nested_update)
        else:
            if not name in context:
                print("ERROR: Reassignment on non-existent variable: {variable}".format(variable=statement.name))
            else:
                scoped_variables[name] = value

    # function call
    elif type(statement) is AstNodeFunctionCall:
        if type(statement.name) is AstNodeNamespaceAccess:
            namespace = evaluate_expression(statement.name, context)
            function = namespace["function"]
            context["self"] = namespace["self"]
        else:
            function = context[statement.name]

        # in-built
        if callable(function):
            return_value = function(*[evaluate_expression(parameter, context) for parameter in statement.parameters])
            if return_value:
                scoped_variables = return_value

        # else
        else:
            call_parameters = to_parameters_dict(statement.parameters, context)
            declaration_parameters = to_parameters_dict(function.parameters, context)

            parameters = {}
            for idx, key in enumerate(declaration_parameters.keys()):
                if key in call_parameters:
                    parameters[key] = evaluate_expression(call_parameters[key], context)
                else:
                    parameters[key] = evaluate_expression(call_parameters[idx], context)

            statements = {}
            for body_statement in function.body:
                call_context_parameters = context | parameters | statements
                if type(body_statement) is AstNodeReturnStatement:
                    scoped_variables = evaluate_expression(
                        body_statement.expression,
                        call_context_parameters
                    )
                else:
                    statements |= evaluate_statement(body_statement, call_context_parameters)

    # pipe
    elif type(statement) is AstNodePipe:
        left = evaluate_statement(statement.left, context)
        right = evaluate_statement(statement.right, context | {"$": left})

        scoped_variables = right

    # namespace access
    elif type(statement) is AstNodeNamespaceAccess:
        left = evaluate_expression(statement.left, context)
        right = evaluate_expression(statement.right, left)

        self = list(context.keys())[list(context.values()).index(left)]

        if type(right) is AstNodeFunctionDeclaration:
            scoped_variables = {"self": self, "function": right}
        else:
            scoped_variables = right

    # if
    elif type(statement) is AstNodeIf:
        for arm in statement.arms:
            comparison = evaluate_expression(arm.comparison, context)

            if comparison:
                for arm_statement in arm.body:
                    scoped_variables |= evaluate_statement(arm_statement, context)
                break


    return scoped_variables


def evaluate_expression(expression, scoped_variables):
    result = expression

    # operator expression
    if type(expression) is AstNodeOperatorExpression:
        left = evaluate_expression(expression.left, scoped_variables)
        right = evaluate_expression(expression.right, scoped_variables)

        if type(left) != type(right):
            print("ERROR: Can't do math with non-matching types. Left: {left} - Right: {right}".format(left=type(left), right=type(right)))
        else:
            if expression.type == "+":
                result = left + right
            elif expression.type == "-":
                result = left - right
            elif expression.type == "*":
                result = left * right
            elif expression.type == "/":
                result = left / right

    # general expression
    elif type(expression) is AstNodeExpression:
        if expression.type is AstNodeExpressionType.IDENTIFIER:
            if expression.value == "self":
                result = scoped_variables[scoped_variables["self"]]
            elif "NAMESPACE_ACCESS" in scoped_variables:
                result = expression.value
            else:
                result = scoped_variables[expression.value]
        elif expression.type is AstNodeExpressionType.ARRAY:
            result = [evaluate_expression(element.value, scoped_variables) for element in expression.value]
        elif expression.type is AstNodeExpressionType.MAP:
            result = {}
            for element in expression.value:
                result[evaluate_expression(element.key, scoped_variables)] = evaluate_expression(element.value, scoped_variables)
        else:
            result = evaluate_expression(expression.value, scoped_variables)

    # function call / type instantiation
    elif type(expression) is AstNodeFunctionCall:
        if type(expression.name) is AstNodeNamespaceAccess:
            namespace = evaluate_expression(expression.name, scoped_variables)
            function = namespace["function"]
            scoped_variables["self"] = namespace["self"]
        else:
            function = scoped_variables[expression.name]

        # custom function call
        if type(function) is AstNodeFunctionDeclaration:
            result = evaluate_statement(expression, scoped_variables)

        # in-built function call
        elif callable(function):
            result = evaluate_statement(expression, scoped_variables)

        # type instantiation
        elif type(function) is dict:
            instance_variables = evaluate_expression(function, scoped_variables)
            result = instance_variables

            variable_type = types[expression.name]
            if type(variable_type) is AstNodeVariableTypeType:
                type_type = evaluate_expression(variable_type.base_type, scoped_variables)
                result |= type_type

    # function call parameter
    elif type(expression) is AstNodeFunctionCallParameter:
        result = evaluate_expression(expression.value, scoped_variables)
        if result == "$":
            result = scoped_variables["$"]

    # namespace access
    elif type(expression) is AstNodeNamespaceAccess:
        if "NAMESPACE_ACCESS" in scoped_variables:
            result = get_namespace_path(expression, scoped_variables)
        else:
            result = evaluate_statement(expression, scoped_variables)

    # type declaration
    elif type(expression) is AstNodeTypeDeclaration:
        instance_variables = {}
        for node in expression.body:
            instance_variables |= evaluate_statement(node, scoped_variables)

        result = instance_variables

    # comparison
    elif type(expression) is AstNodeCompare:
        left = evaluate_expression(expression.left, scoped_variables)
        right = evaluate_expression(expression.right, scoped_variables)

        if expression.comparator == "==":
            result = left == right
        elif expression.comparator == "!=":
            result = left != right
        elif expression.comparator == ">":
            result = left > right
        elif expression.comparator == "<":
            result = left < right
        elif expression.comparator == ">=":
            result = left >= right
        elif expression.comparator == "<=":
            result = left <= right
        else:
            print("ERROR: Couldn't evaluate comparison expression")
    elif type(expression) is AstNodeCompareExpressions:
        left = evaluate_expression(expression.left, scoped_variables)
        right = evaluate_expression(expression.right, scoped_variables)

        if expression.operator == "and":
            result = left and right
        elif expression.operator == "or":
            result = left or right


    return result



def interpret(parsed_result, context):
    for node in parsed_result:
        if args.debug:
            print(node)

        context |= evaluate_statement(node, context)

    return context


if result:
    interpret(result, variables.copy())




# if __name__ == "__main__":
#     lex.runmain()