EBNFCompiler.py 8.95 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python

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


from functools import partial
import os
import sys
13

eckhart's avatar
eckhart committed
14
sys.path.extend(['../', '../../', './'])
15

16
17
18
19
try:
    import regex as re
except ImportError:
    import re
20
from DHParser import is_filename, load_if_file, \
21
    Grammar, Compiler, nil_preprocessor, \
di68kap's avatar
di68kap committed
22
23
    Lookbehind, Lookahead, Alternative, Pop, Required, Token, Synonym, \
    Option, NegativeLookbehind, OneOrMore, RegExp, Retrieve, Series, Capture, \
24
25
    ZeroOrMore, Forward, NegativeLookahead, mixin_comment, compile_source, \
    last_value, counterpart, accumulate, PreprocessorFunc, \
26
    Node, TransformationFunc, TransformationDict, Whitespace, \
eckhart's avatar
eckhart committed
27
    traverse, remove_children_if, is_anonymous, \
Eckhart Arnold's avatar
Eckhart Arnold committed
28
    reduce_single_child, replace_by_single_child, replace_or_reduce, remove_whitespace, \
29
    remove_expendables, remove_empty, remove_tokens, flatten, is_insignificant_whitespace, \
30
    is_empty, is_expendable, collapse, replace_content, WHITESPACE_PTYPE, TOKEN_PTYPE, \
eckhart's avatar
eckhart committed
31
    remove_nodes, remove_content, remove_brackets, replace_parser, \
di68kap's avatar
di68kap committed
32
    keep_children, is_one_of, has_content, apply_if, remove_first, remove_last, \
eckhart's avatar
eckhart committed
33
    forbid, assert_content, remove_infix_operator, GLOBALS
34
from DHParser.log import logging
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56


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

def EBNFPreprocessor(text):
    return text

def get_preprocessor() -> PreprocessorFunc:
    return EBNFPreprocessor


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

class EBNFGrammar(Grammar):
eckhart's avatar
eckhart committed
57
    r"""Parser for an EBNF source file.
58
59
    """
    expression = Forward()
60
    source_hash__ = "7ca2bbabfc9bc19ec54e2318bbc4c9c2"
61
    static_analysis_pending__ = False
eckhart's avatar
eckhart committed
62
    parser_initialization__ = ["upon instantiation"]
eckhart's avatar
eckhart committed
63
    resume_rules__ = {}
64
65
    COMMENT__ = r'#.*(?:\n|$)'
    WHITESPACE__ = r'\s*'
66
    WSP_RE__ = mixin_comment(whitespace=WHITESPACE__, comment=COMMENT__)
di68kap's avatar
di68kap committed
67
    wsp__ = Whitespace(WSP_RE__)
68
    EOF = NegativeLookahead(RegExp('.'))
di68kap's avatar
di68kap committed
69
70
71
    whitespace = Series(RegExp('~'), wsp__)
    regexp = Series(RegExp('/(?:\\\\/|[^/])*?/'), wsp__)
    plaintext = Series(RegExp('`(?:[^"]|\\\\")*?`'), wsp__)
eckhart's avatar
eckhart committed
72
    literal = Alternative(Series(RegExp('"(?:[^"]|\\\\")*?"'), wsp__), Series(RegExp("'(?:[^']|\\\\')*?'"), wsp__))
di68kap's avatar
di68kap committed
73
74
75
76
77
78
79
    symbol = Series(RegExp('(?!\\d)\\w+'), wsp__)
    option = Series(Series(Token("["), wsp__), expression, Series(Token("]"), wsp__), mandatory=1)
    repetition = Series(Series(Token("{"), wsp__), expression, Series(Token("}"), wsp__), mandatory=1)
    oneormore = Series(Series(Token("{"), wsp__), expression, Series(Token("}+"), wsp__))
    unordered = Series(Series(Token("<"), wsp__), expression, Series(Token(">"), wsp__), mandatory=1)
    group = Series(Series(Token("("), wsp__), expression, Series(Token(")"), wsp__), mandatory=1)
    retrieveop = Alternative(Series(Token("::"), wsp__), Series(Token(":"), wsp__))
eckhart's avatar
eckhart committed
80
81
    flowmarker = Alternative(Series(Token("!"), wsp__), Series(Token("&"), wsp__), Series(Token("-!"), wsp__), Series(Token("-&"), wsp__))
    factor = Alternative(Series(Option(flowmarker), Option(retrieveop), symbol, NegativeLookahead(Series(Token("="), wsp__))), Series(Option(flowmarker), literal), Series(Option(flowmarker), plaintext), Series(Option(flowmarker), regexp), Series(Option(flowmarker), whitespace), Series(Option(flowmarker), oneormore), Series(Option(flowmarker), group), Series(Option(flowmarker), unordered), repetition, option)
di68kap's avatar
di68kap committed
82
83
    term = OneOrMore(Series(Option(Series(Token("§"), wsp__)), factor))
    expression.set(Series(term, ZeroOrMore(Series(Series(Token("|"), wsp__), term))))
eckhart's avatar
eckhart committed
84
    directive = Series(Series(Token("@"), wsp__), symbol, Series(Token("="), wsp__), Alternative(regexp, literal, symbol), ZeroOrMore(Series(Series(Token(","), wsp__), Alternative(regexp, literal, symbol))), mandatory=1)
di68kap's avatar
di68kap committed
85
86
    definition = Series(symbol, Series(Token("="), wsp__), expression, mandatory=1)
    syntax = Series(Option(Series(wsp__, RegExp(''))), ZeroOrMore(Alternative(definition, directive)), EOF, mandatory=2)
87
88
89
    root__ = syntax
    
def get_grammar() -> EBNFGrammar:
90
    global GLOBALS
91
    try:
92
        grammar = GLOBALS.EBNF_00000001_grammar_singleton
eckhart's avatar
eckhart committed
93
    except AttributeError:
94
        GLOBALS.EBNF_00000001_grammar_singleton = EBNFGrammar()
95
        if hasattr(get_grammar, 'python_src__'):
96
97
            GLOBALS.EBNF_00000001_grammar_singleton.python_src__ = get_grammar.python_src__
        grammar = GLOBALS.EBNF_00000001_grammar_singleton
98
99
100
101
102
103
104
105
106
107
    return grammar


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

EBNF_AST_transformation_table = {
di68kap's avatar
di68kap committed
108
    # AST Transformations for EBNF-grammar
109
    "<":
di68kap's avatar
di68kap committed
110
111
112
113
        remove_expendables,
    "syntax":
        [],  # otherwise '"*": replace_by_single_child' would be applied
    "directive, definition":
eckhart's avatar
eckhart committed
114
        remove_tokens('@', '=', ','),
di68kap's avatar
di68kap committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
    "expression":
        [replace_by_single_child, flatten, remove_tokens('|')],  # remove_infix_operator],
    "term":
        [replace_by_single_child, flatten],  # supports both idioms:
                                             # "{ factor }+" and "factor { factor }"
    "factor, flowmarker, retrieveop":
        replace_by_single_child,
    "group":
        [remove_brackets, replace_by_single_child],
    "unordered":
        remove_brackets,
    "oneormore, repetition, option":
        [reduce_single_child, remove_brackets,
         forbid('repetition', 'option', 'oneormore'), assert_content(r'(?!§)(?:.|\n)*')],
    "symbol, literal, regexp":
        reduce_single_child,
    (TOKEN_PTYPE, WHITESPACE_PTYPE):
        reduce_single_child,
    "*":
        replace_by_single_child
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
}


def EBNFTransform() -> TransformationDict:
    return partial(traverse, processing_table=EBNF_AST_transformation_table.copy())

def get_transformer() -> TransformationFunc:
    global thread_local_EBNF_transformer_singleton
    try:
        transformer = thread_local_EBNF_transformer_singleton
    except NameError:
        thread_local_EBNF_transformer_singleton = EBNFTransform()
        transformer = thread_local_EBNF_transformer_singleton
    return transformer


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

class EBNFCompiler(Compiler):
    """Compiler for the abstract-syntax-tree of a EBNF source file.
    """
    def on_syntax(self, node):
        return node

    def on_definition(self, node):
        pass

    def on_directive(self, node):
        pass

    def on_expression(self, node):
        pass

    def on_term(self, node):
        pass

    def on_factor(self, node):
        pass

    def on_flowmarker(self, node):
        pass

    def on_retrieveop(self, node):
        pass

    def on_group(self, node):
        pass

    def on_oneormore(self, node):
        pass

    def on_repetition(self, node):
        pass

    def on_option(self, node):
        pass

    def on_symbol(self, node):
        pass

    def on_literal(self, node):
        pass

    def on_regexp(self, node):
        pass

    def on_list_(self, node):
        pass

    def on_EOF(self, node):
        pass


eckhart's avatar
eckhart committed
212
def get_compiler() -> EBNFCompiler:
213
214
215
216
    global thread_local_EBNF_compiler_singleton
    try:
        compiler = thread_local_EBNF_compiler_singleton
    except NameError:
eckhart's avatar
eckhart committed
217
        thread_local_EBNF_compiler_singleton = EBNFCompiler()
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
        compiler = thread_local_EBNF_compiler_singleton
    return compiler


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


def compile_src(source):
    """Compiles ``source`` and returns (result, errors, ast).
    """
    with logging("LOGS"):
        compiler = get_compiler()
        cname = compiler.__class__.__name__
        log_file_name = os.path.basename(os.path.splitext(source)[0]) \
            if is_filename(source) < 0 else cname[:cname.find('.')] + '_out'    
        result = compile_source(source, get_preprocessor(), 
                                get_grammar(),
                                get_transformer(), compiler)
    return result


if __name__ == "__main__":
    if len(sys.argv) > 1:
        result, errors, ast = compile_src(sys.argv[1])
        if errors:
            for error in errors:
                print(error)
            sys.exit(1)
        else:
251
            print(result.as_sxpr() if isinstance(result, Node) else result)
252
253
    else:
        print("Usage: EBNFCompiler.py [FILENAME]")