aboutsummaryrefslogtreecommitdiff
path: root/core/operators.nom
blob: 7d3f79ff4d36f41256c4f71b20119e6a0dae6326 (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
#..
    This file contains definitions of operators like "+" and "and".

use "core/metaprogramming.nom"

# Indexing:
immediately:
    #.. NOTE!!! It's critical that there are spaces around %key if it's a string,
        otherwise, Lua will get confused and interpret %obj[[[foo]]] as %obj("[foo]")
        instead of %obj[ "foo" ].
        It's also critical to have parens around %obj, otherwise Lua is too dumb to
        realize that {x=1}["x"] is the same as ({x=1})["x"] or that
        {x=1}.x is the same as ({x=1}).x
    parse [..]
        %obj' %key, %obj's %key, %key in %obj, %key'th in %obj, %key of %obj,
        %key st in %obj, %key nd in %obj, %key rd in %obj, %key th in %obj,
    ..as: %obj.%key

# Comparison Operators
immediately:
    compile [%x < %y] to {expr:"(\(%x as lua expr) < \(%y as lua expr))"}
    compile [%x > %y] to {expr:"(\(%x as lua expr) > \(%y as lua expr))"}
    compile [%x <= %y] to {expr:"(\(%x as lua expr) <= \(%y as lua expr))"}
    compile [%x >= %y] to {expr:"(\(%x as lua expr) >= \(%y as lua expr))"}
    # TODO: optimize case of [%x,%y] = [1,2]
    compile [%a is %b, %a = %b, %a == %b] to:
        lua> ".."
            local safe = {Text=true, Number=true};
            local a_lua, b_lua = nomsu:tree_to_lua(\%a).expr, nomsu:tree_to_lua(\%b).expr;
            if safe[\%a.type] or safe[\%b.type] then
                return {expr="("..a_lua.." == "..b_lua..")"};
            else
                return {expr="utils.equivalent("..a_lua..", "..b_lua..")"};
            end
    compile [%a isn't %b, %a is not %b, %a not= %b, %a != %b] to:
        lua> ".."
            local safe = {Text=true, Number=true};
            local a_lua, b_lua = nomsu:tree_to_lua(\%a).expr, nomsu:tree_to_lua(\%b).expr;
            if safe[\%a.type] or safe[\%b.type] then
                return {expr="("..a_lua.." ~= "..b_lua..")"};
            else
                return {expr="(not utils.equivalent("..a_lua..", "..b_lua.."))"};
            end
    # For strict identity checking, use (%x's id) is (%y's id)
    compile [%'s id, id of %] to {expr:"nomsu.ids[\(% as lua expr)]"}

# Variable assignment operator
immediately:
    compile [%var <- %value] to:
        lua> "local \%var_lua = nomsu:tree_to_lua(\%var);"
        assume %var_lua.expr or barf "Invalid target for assignment: \(%var's source code)"
        lua> "local \%value_lua = nomsu:tree_to_lua(\%value);"
        assume %value_lua.expr or barf "Invalid value for assignment: \(%value's source code)"
        return {..}
            statements:"\(%var_lua.expr) = \(%value_lua.expr);"
            locals: =lua "(\%var.type == 'Var' and {\%var_lua.expr} or nil)"

immediately:
    # Simultaneous mutli-assignments like: x,y,z = 1,x,3;
    compile [<- %assignments] to:
        %locals <- []
        %targets <- []
        %values <- []
        assume ((%assignments' "type") is "Dict") or barf ".."
            Expected a Dict for the assignments part of '<- %' statement, not \(%assignments' source code)
        lua> ".."
            for i, item in ipairs(\%assignments.value) do
                local target, value = item.key, item.value;
                local target_lua = nomsu:tree_to_lua(target);
                if not target_lua.expr then error("Invalid target for assignment: "..target:get_src()); end
                local value_lua = nomsu:tree_to_lua(value);
                if not value_lua.expr then error("Invalid value for assignment: "..value:get_src()); end
                if target.type == "Var" then
                    table.insert(\%locals, target_lua.expr);
                end
                table.insert(\%targets, target_lua.expr);
                table.insert(\%values, value_lua.expr);
            end
            utils.deduplicate(\%locals);
            return {locals=\%locals, statements=(table.concat(\%targets, ", ").." = "..table.concat(\%values, ", ")..";")};

immediately:
    compile [export %var <- %value] to:
        %var_lua <- (%var as lua)
        assume %var_lua.expr or barf "Invalid target for assignment: \(%var's source code)"
        %value_lua <- (%value as lua)
        assume %value_lua.expr or barf "Invalid value for assignment: \(%value's source code)"
        return {statements:"\(%var_lua.expr) = \(%value_lua.expr);"}

    compile [exporting %exported %body] to:
        %body_lua <- (%body as lua)
        %leftover_locals <- (=lua "{unpack(\%body_lua.locals or {})}")
        assume (%exported.type = "List") or barf ".."
            Expected a List for the export part of 'exporting' statement, not \(%exported's source code)
        lua> ".."
            for i, item in ipairs(\%exported.value) do
                if item.type ~= "Var" then
                    error("'exporting' statement expects Vars, not: "..item:get_src());
                end
                local var = nomsu:tree_to_lua(item).expr;
                utils.remove_from_list(\%leftover_locals, var);
            end
        return {locals:%leftover_locals, statements:=lua "\%body_lua.statements or (\%body_lua.expr..';')"}

    compile [with %assignments %body] to:
        %body_lua <- (%body as lua)
        %locals <- []
        %declarations <- []
        %leftover_locals <- (=lua "{unpack(\%body_lua.locals or {})}")
        assume ((%assignments' "type") is "List") or barf ".."
            Expected a List for the assignments part of 'with' statement, not \(%assignments' source code)
        lua> ".."
            for i, item in ipairs(\%assignments.value) do
                if item.type == "Var" then
                    local var = nomsu:tree_to_lua(item).expr;
                    utils.remove_from_list(\%leftover_locals, var);
                    table.insert(\%locals, var);
                else
                    if not (item.type == "FunctionCall" and #item.value == 3 and item.value[2].value == "<-") then
                        error("'with' statement expects entries of the form: '%var <- %value', not: "..item:get_src());
                    end
                    local target, value = item.value[1], item.value[3];
                    local target_lua = nomsu:tree_to_lua(target);
                    if not target_lua.expr then error("Invalid target for assignment: "..target:get_src()); end
                    local value_lua = nomsu:tree_to_lua(value);
                    if not value_lua.expr then error("Invalid value for assignment: "..value:get_src()); end
                    if target.type == "Var" then
                        utils.remove_from_list(\%leftover_locals, target_lua.expr);
                    end
                    table.insert(\%declarations, (("local %s = %s;\\n    "):format(
                        target_lua.expr, value_lua.expr)));
                end
            end
            local locals_code = "";
            if #\%locals > 0 then
                locals_code = "\\nlocal "..table.concat(\%locals, ", ")..";";
            end
            local declaration_code = "";
            if #\%declarations > 0 then
                declaration_code = "\\n"..table.concat(\%declarations, "\\n");
            end
            return {locals=\%leftover_locals, statements=([[
            do%s%s
            %s
            end]]):format(locals_code, declaration_code, \%body_lua.statements or (\%body_lua.expr..";"))};

immediately:
    # Math Operators
    compile [%x + %y] to {expr:"(\(%x as lua expr) + \(%y as lua expr))"}
    compile [%x - %y] to {expr:"(\(%x as lua expr) - \(%y as lua expr))"}
    compile [%x * %y] to {expr:"(\(%x as lua expr) * \(%y as lua expr))"}
    compile [%x / %y] to {expr:"(\(%x as lua expr) / \(%y as lua expr))"}
    compile [%x ^ %y] to {expr:"(\(%x as lua expr) ^ \(%y as lua expr))"}
    compile [%x wrapped around %y, %x mod %y] to {expr:"(\(%x as lua expr) % \(%y as lua expr))"}

    # 3-part chained comparisons
    # (uses a lambda to avoid re-evaluating middle value, while still being an expression)
    parse [%x <  %y <  %z] as: =lua "(function(x,y,z) return x <  y and y <  z; end)(\%x,\%y,\%z)"
    parse [%x <= %y <  %z] as: =lua "(function(x,y,z) return x <= y and y <  z; end)(\%x,\%y,\%z)"
    parse [%x <  %y <= %z] as: =lua "(function(x,y,z) return x <  y and y <= z; end)(\%x,\%y,\%z)"
    parse [%x <= %y <= %z] as: =lua "(function(x,y,z) return x <= y and y <= z; end)(\%x,\%y,\%z)"
    parse [%x >  %y >  %z] as: =lua "(function(x,y,z) return x >  y and y >  z; end)(\%x,\%y,\%z)"
    parse [%x >= %y >  %z] as: =lua "(function(x,y,z) return x >= y and y >  z; end)(\%x,\%y,\%z)"
    parse [%x >  %y >= %z] as: =lua "(function(x,y,z) return x >  y and y >= z; end)(\%x,\%y,\%z)"
    parse [%x >= %y >= %z] as: =lua "(function(x,y,z) return x >= y and y >= z; end)(\%x,\%y,\%z)"
    # TODO: optimize for common case where x,y,z are all either variables or number literals

    # Boolean Operators
    compile [%x and %y] to {expr:"(\(%x as lua expr) and \(%y as lua expr))"}
    compile [%x or %y] to {expr:"(\(%x as lua expr) or \(%y as lua expr))"}

    # Bitwise Operators
    compile [%a OR %b, %a | %b] to {expr:"bit32.bor(\(%a as lua expr), \(%b as lua expr))"}
    compile [%a XOR %b] to {expr:"bit32.bxor(\(%a as lua expr), \(%b as lua expr))"}
    compile [%a AND %b, %a & %b] to {expr:"bit32.band(\(%a as lua expr), \(%b as lua expr))"}
    compile [NOT %, ~ %] to {expr:"bit32.bnot(\(% as lua expr))"}
    compile [%x LSHIFT %shift, %x << %shift] to {expr:"bit32.lshift(\(%x as lua expr), \(%shift as lua expr))"}
    compile [%x RSHIFT %shift, %x >>> %shift] to {expr:"bit32.rshift(\(%x as lua expr), \(%shift as lua expr))"}
    compile [%x ARSHIFT %shift, %x >> %shift] to {expr:"bit32.arshift(\(%x as lua expr), \(%shift as lua expr))"}
    # TODO: implement OR, XOR, AND for multiple operands?

    # Unary operators
    compile [- %] to {expr:"(- \(% as lua expr))"}
    compile [not %] to {expr:"(not \(% as lua expr))"}

# Update operators
immediately:
    parse [%var + <- %, %var +<- %] as: %var <- (%var + %)
    parse [%var - <- %, %var -<- %] as: %var <- (%var - %)
    parse [%var * <- %, %var *<- %] as: %var <- (%var * %)
    parse [%var / <- %, %var /<- %] as: %var <- (%var / %)
    parse [%var ^ <- %, %var ^<- %] as: %var <- (%var ^ %)
    parse [%var and <- %] as: %var <- (%var and %)
    parse [%var or <- %] as: %var <- (%var or %)
    parse [wrap %var around %] as: %var <- (%var wrapped around %)