ArithmeticRightRecursiveCompiler.py 9.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python3

#######################################################################
#
# SYMBOLS SECTION - Can be edited. Changes will be preserved.
#
#######################################################################


import collections
from functools import partial
import os
import sys

15
sys.path.extend(['../../', '../', './'])
16
17
18
19
20
21
22
23
24
25
26
27
28
29

try:
    import regex as re
except ImportError:
    import re
from DHParser import logging, is_filename, load_if_file, \
    Grammar, Compiler, nil_preprocessor, PreprocessorToken, Whitespace, DropWhitespace, \
    Lookbehind, Lookahead, Alternative, Pop, Token, DropToken, Synonym, AllOf, SomeOf, \
    Unordered, Option, NegativeLookbehind, OneOrMore, RegExp, Retrieve, Series, Capture, \
    ZeroOrMore, Forward, NegativeLookahead, Required, mixin_comment, compile_source, \
    grammar_changed, last_value, counterpart, accumulate, PreprocessorFunc, \
    Node, TransformationFunc, TransformationDict, transformation_factory, traverse, \
    remove_children_if, move_adjacent, normalize_whitespace, is_anonymous, matches_re, \
    reduce_single_child, replace_by_single_child, replace_or_reduce, remove_whitespace, \
30
    remove_empty, remove_tokens, flatten, is_insignificant_whitespace, is_empty, lean_left, \
Eckhart Arnold's avatar
Eckhart Arnold committed
31
32
    collapse, collapse_if, replace_content, WHITESPACE_PTYPE, TOKEN_PTYPE, \
    remove_nodes, remove_content, remove_brackets, change_tag_name, remove_anonymous_tokens, \
33
34
35
    keep_children, is_one_of, not_one_of, has_content, apply_if, remove_first, remove_last, \
    remove_anonymous_empty, keep_nodes, traverse_locally, strip, lstrip, rstrip, \
    replace_content, replace_content_by, forbid, assert_content, remove_infix_operator, \
Eckhart Arnold's avatar
Eckhart Arnold committed
36
    error_on, recompile_grammar, GLOBALS
37
38
39
40
41
42
43
44


#######################################################################
#
# PREPROCESSOR SECTION - Can be edited. Changes will be preserved.
#
#######################################################################

45
def ArithmeticRightRecursivePreprocessor(text):
46
47
48
    return text, lambda i: i

def get_preprocessor() -> PreprocessorFunc:
49
    return ArithmeticRightRecursivePreprocessor
50
51
52
53
54
55
56
57


#######################################################################
#
# PARSER SECTION - Don't edit! CHANGES WILL BE OVERWRITTEN!
#
#######################################################################

58
59
class ArithmeticRightRecursiveGrammar(Grammar):
    r"""Parser for an ArithmeticRightRecursive source file.
60
    """
61
    element = Forward()
62
    expression = Forward()
63
    sign = Forward()
64
    tail = Forward()
Eckhart Arnold's avatar
Eckhart Arnold committed
65
    term = Forward()
66
    source_hash__ = "57a303f28ffb50a84b86e98c71ea2e32"
67
68
69
70
71
72
73
    static_analysis_pending__ = [True]
    parser_initialization__ = ["upon instantiation"]
    resume_rules__ = {}
    COMMENT__ = r'#.*'
    WHITESPACE__ = r'\s*'
    WSP_RE__ = mixin_comment(whitespace=WHITESPACE__, comment=COMMENT__)
    dwsp__ = DropWhitespace(WSP_RE__)
74
    VARIABLE = RegExp('[a-dj-z]')
75
    NUMBER = RegExp('(?:0|(?:[1-9]\\d*))(?:\\.\\d+)?')
Eckhart Arnold's avatar
Eckhart Arnold committed
76
77
    MINUS = RegExp('-')
    PLUS = RegExp('\\+')
78
    i = Token("i")
79
80
81
    e = Token("e")
    pi = Alternative(DropToken("pi"), DropToken("π"))
    special = Alternative(pi, e)
82
    number = Synonym(NUMBER)
83
84
85
86
87
88
89
    log = Series(Series(DropToken('log('), dwsp__), expression, DropToken(")"), mandatory=1)
    tan = Series(Series(DropToken('tan('), dwsp__), expression, DropToken(")"), mandatory=1)
    cos = Series(Series(DropToken('cos('), dwsp__), expression, DropToken(")"), mandatory=1)
    sin = Series(Series(DropToken('sin('), dwsp__), expression, DropToken(")"), mandatory=1)
    function = Alternative(sin, cos, tan, log)
    group = Series(DropToken("("), expression, DropToken(")"), mandatory=1)
    tail_value = Alternative(special, function, VARIABLE, group)
90
    tail_pow = Series(tail_value, Option(i), DropToken("^"), element)
91
    tail_elem = Alternative(tail_pow, tail_value)
92
    value = Series(Alternative(number, tail_value), Option(i))
93
    pow = Series(value, DropToken("^"), Option(sign), element)
94
95
    element.set(Alternative(pow, value))
    sign.set(Alternative(PLUS, MINUS))
96
    seq = Series(tail_elem, tail)
97
    tail.set(Series(Alternative(seq, tail_elem), Option(i)))
98
    factor = Series(Option(sign), Alternative(Series(Option(element), tail), element), dwsp__)
99
    div = Series(factor, Series(DropToken("/"), dwsp__), term)
100
    mul = Series(factor, Series(DropToken("*"), dwsp__), term)
101
102
103
104
    term.set(Alternative(mul, div, factor))
    sub = Series(term, Series(DropToken("-"), dwsp__), expression)
    add = Series(term, Series(DropToken("+"), dwsp__), expression)
    expression.set(Alternative(add, sub, term))
105
106
    root__ = expression
    
107
def get_grammar() -> ArithmeticRightRecursiveGrammar:
108
    try:
109
        grammar = GLOBALS.ArithmeticRightRecursive_00000001_grammar_singleton
110
    except AttributeError:
111
        GLOBALS.ArithmeticRightRecursive_00000001_grammar_singleton = ArithmeticRightRecursiveGrammar()
112
        if hasattr(get_grammar, 'python_src__'):
113
114
            GLOBALS.ArithmeticRightRecursive_00000001_grammar_singleton.python_src__ = get_grammar.python_src__
        grammar = GLOBALS.ArithmeticRightRecursive_00000001_grammar_singleton
115
116
117
118
119
120
121
122
123
    return grammar


#######################################################################
#
# AST SECTION - Can be edited. Changes will be preserved.
#
#######################################################################

Eckhart Arnold's avatar
Eckhart Arnold committed
124

125
126
ArithmeticRightRecursive_AST_transformation_table = {
    # AST Transformations for the ArithmeticRightRecursive-grammar
Eckhart Arnold's avatar
Eckhart Arnold committed
127
    # "<": flatten_anonymous_nodes,
128
129
130
131
132
133
134
    "special, number, function, tail_value, tail_elem, tail, value, "
    "element, factor, term, expression":
        [replace_by_single_child],
    "pi": [replace_content_by('π')],
    "tail_pow": [change_tag_name('pow')],
    "add, sub": [lean_left({'sub', 'add'})],
    "mul, div": [lean_left({'mul', 'div'})]
135
136
137
}


138
139
140
141
142
143
144
145
146
147
148
149
def ArithmeticRightRecursiveTransform() -> TransformationFunc:
    def transformation_func(cst: Node, pass_1, pass_2):
        """Special transformation function requires two passes, because
        otherwise elimination of grouping nodes (pass 2) would interfere
        with the adjustment of the tree structure to the left-associativity
        of the `add`, `sub`, `mul` and `div` operators."""
        traverse(cst, pass_1)
        traverse(cst, pass_2)
    return partial(transformation_func,
                   pass_1=ArithmeticRightRecursive_AST_transformation_table.copy(),
                   pass_2={'group': [replace_by_single_child]}.copy())

150
151
152

def get_transformer() -> TransformationFunc:
    try:
153
        transformer = GLOBALS.ArithmeticRightRecursive_00000001_transformer_singleton
154
    except AttributeError:
155
156
157
        GLOBALS.ArithmeticRightRecursive_00000001_transformer_singleton = \
            ArithmeticRightRecursiveTransform()
        transformer = GLOBALS.ArithmeticRightRecursive_00000001_transformer_singleton
158
159
160
161
162
163
164
165
166
    return transformer


#######################################################################
#
# COMPILER SECTION - Can be edited. Changes will be preserved.
#
#######################################################################

167
168
class ArithmeticRightRecursiveCompiler(Compiler):
    """Compiler for the abstract-syntax-tree of a ArithmeticRightRecursive source file.
169
170
171
    """

    def __init__(self):
172
        super(ArithmeticRightRecursiveCompiler, self).__init__()
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192

    def _reset(self):
        super()._reset()
        # initialize your variables here, not in the constructor!
    def on_expression(self, node):
        return self.fallback_compiler(node)

    # def on_term(self, node):
    #     return node

    # def on_factor(self, node):
    #     return node

    # def on_NUMBER(self, node):
    #     return node

    # def on_VARIABLE(self, node):
    #     return node


193
def get_compiler() -> ArithmeticRightRecursiveCompiler:
194
    try:
195
        compiler = GLOBALS.ArithmeticRightRecursive_00000001_compiler_singleton
196
    except AttributeError:
197
198
        GLOBALS.ArithmeticRightRecursive_00000001_compiler_singleton = ArithmeticRightRecursiveCompiler()
        compiler = GLOBALS.ArithmeticRightRecursive_00000001_compiler_singleton
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
    return compiler


#######################################################################
#
# END OF DHPARSER-SECTIONS
#
#######################################################################


def compile_src(source, log_dir=''):
    """Compiles ``source`` and returns (result, errors, ast).
    """
    with logging(log_dir):
        compiler = get_compiler()
        cname = compiler.__class__.__name__
        result_tuple = compile_source(source, get_preprocessor(),
                                      get_grammar(),
                                      get_transformer(), compiler)
    return result_tuple


if __name__ == "__main__":
    # recompile grammar if needed
    grammar_path = os.path.abspath(__file__).replace('Compiler.py', '.ebnf')
    if os.path.exists(grammar_path):
        if not recompile_grammar(grammar_path, force=False,
                                  notify=lambda:print('recompiling ' + grammar_path)):
            error_file = os.path.basename(__file__).replace('Compiler.py', '_ebnf_ERRORS.txt')
            with open(error_file, encoding="utf-8") as f:
                print(f.read())
            sys.exit(1)
    else:
        print('Could not check whether grammar requires recompiling, '
              'because grammar was not found at: ' + grammar_path)

    if len(sys.argv) > 1:
        # compile file
        file_name, log_dir = sys.argv[1], ''
        if file_name in ['-d', '--debug'] and len(sys.argv) > 2:
            file_name, log_dir = sys.argv[2], 'LOGS'
        result, errors, ast = compile_src(file_name, log_dir)
        if errors:
            cwd = os.getcwd()
            rel_path = file_name[len(cwd):] if file_name.startswith(cwd) else file_name
            for error in errors:
                print(rel_path + ':' + str(error))
            sys.exit(1)
        else:
            print(result.as_xml() if isinstance(result, Node) else result)
    else:
250
        print("Usage: ArithmeticRightRecursiveCompiler.py [FILENAME]")