2.12.2021, 9:00 - 11:00: Due to updates GitLab may be unavailable for some minutes between 09:00 and 11:00.

XMLCompiler.py 26.9 KB
Newer Older
eckhart's avatar
eckhart committed
1
2
3
4
5
6
7
8
9
#!/usr/bin/python

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


Eckhart Arnold's avatar
Eckhart Arnold committed
10
from collections import OrderedDict
eckhart's avatar
eckhart committed
11
12
13
14
from functools import partial
import os
import sys

Eckhart Arnold's avatar
Eckhart Arnold committed
15

di68kap's avatar
di68kap committed
16
sys.path.extend(['../', '../../'])
eckhart's avatar
eckhart committed
17
18
19
20
21
22
23

try:
    import regex as re
except ImportError:
    import re
from DHParser import logging, is_filename, load_if_file, \
    Grammar, Compiler, nil_preprocessor, PreprocessorToken, Whitespace, \
di68kap's avatar
di68kap committed
24
25
    Lookbehind, Lookahead, Alternative, Pop, Synonym, AllOf, SomeOf, Unordered, \
    Option, NegativeLookbehind, OneOrMore, RegExp, Retrieve, Series, Capture, \
eckhart's avatar
eckhart committed
26
27
    ZeroOrMore, Forward, NegativeLookahead, Required, mixin_comment, compile_source, \
    grammar_changed, last_value, counterpart, accumulate, PreprocessorFunc, \
di68kap's avatar
di68kap committed
28
    Node, TransformationFunc, TransformationDict, Token, \
29
    traverse, remove_children_if, is_anonymous, GLOBALS, \
eckhart's avatar
eckhart committed
30
31
32
33
34
    reduce_single_child, replace_by_single_child, replace_or_reduce, remove_whitespace, \
    remove_expendables, remove_empty, remove_tokens, flatten, is_whitespace, \
    is_empty, is_expendable, collapse, replace_content, WHITESPACE_PTYPE, TOKEN_PTYPE, \
    remove_nodes, remove_content, remove_brackets, replace_parser, remove_anonymous_tokens, \
    keep_children, is_one_of, has_content, apply_if, remove_first, remove_last, \
35
    remove_anonymous_empty, keep_nodes, traverse_locally, strip, lstrip, rstrip, PLACEHOLDER
eckhart's avatar
eckhart committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57


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

def XMLPreprocessor(text):
    return text, lambda i: i

def get_preprocessor() -> PreprocessorFunc:
    return XMLPreprocessor


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

class XMLGrammar(Grammar):
58
    r"""Parser for a XML source file.
eckhart's avatar
eckhart committed
59
60
61
62
63
64
65
66
67
68
69
    """
    DeclSep = Forward()
    EncodingDecl = Forward()
    Name = Forward()
    VersionInfo = Forward()
    choice = Forward()
    cp = Forward()
    element = Forward()
    extSubsetDecl = Forward()
    ignoreSectContents = Forward()
    markupdecl = Forward()
70
    source_hash__ = "1c64c8f613952c5ab8e851da15f65ec3"
eckhart's avatar
eckhart committed
71
    parser_initialization__ = ["upon instantiation"]
72
    resume_rules__ = {}
eckhart's avatar
eckhart committed
73
74
    COMMENT__ = r''
    WHITESPACE__ = r'\s*'
75
    WSP_RE__ = mixin_comment(whitespace=WHITESPACE__, comment=COMMENT__)
di68kap's avatar
di68kap committed
76
    wsp__ = Whitespace(WSP_RE__)
eckhart's avatar
eckhart committed
77
78
79
80
    EOF = NegativeLookahead(RegExp('.'))
    S = RegExp('\\s+')
    Char = RegExp('\\x09|\\x0A|\\x0D|[\\u0020-\\uD7FF]|[\\uE000-\\uFFFD]|[\\U00010000-\\U0010FFFF]')
    Chars = RegExp('(?:\\x09|\\x0A|\\x0D|[\\u0020-\\uD7FF]|[\\uE000-\\uFFFD]|[\\U00010000-\\U0010FFFF])+')
di68kap's avatar
di68kap committed
81
    CharRef = Alternative(Series(Token('&#'), RegExp('[0-9]+'), Token(';')), Series(Token('&#x'), RegExp('[0-9a-fA-F]+'), Token(';')))
eckhart's avatar
eckhart committed
82
83
84
85
86
87
88
    CommentChars = RegExp('(?:(?!-)(?:\\x09|\\x0A|\\x0D|[\\u0020-\\uD7FF]|[\\uE000-\\uFFFD]|[\\U00010000-\\U0010FFFF]))+')
    PIChars = RegExp('(?:(?!\\?>)(?:\\x09|\\x0A|\\x0D|[\\u0020-\\uD7FF]|[\\uE000-\\uFFFD]|[\\U00010000-\\U0010FFFF]))+')
    IgnoreChars = RegExp('(?:(?!(?:<!\\[)|(?:\\]\\]>))(?:\\x09|\\x0A|\\x0D|[\\u0020-\\uD7FF]|[\\uE000-\\uFFFD]|[\\U00010000-\\U0010FFFF]))+')
    CData = RegExp('(?:(?!\\]\\]>)(?:\\x09|\\x0A|\\x0D|[\\u0020-\\uD7FF]|[\\uE000-\\uFFFD]|[\\U00010000-\\U0010FFFF]))+')
    CharData = RegExp('(?:(?!\\]\\]>)[^<&])+')
    PubidChars = RegExp("(?:\\x20|\\x0D|\\x0A|[a-zA-Z0-9]|[-'()+,./:=?;!*#@$_%])+")
    PubidCharsSingleQuoted = RegExp('(?:\\x20|\\x0D|\\x0A|[a-zA-Z0-9]|[-()+,./:=?;!*#@$_%])+')
di68kap's avatar
di68kap committed
89
    CDSect = Series(Token('<![CDATA['), CData, Token(']]>'))
eckhart's avatar
eckhart committed
90
    PITarget = Series(NegativeLookahead(RegExp('X|xM|mL|l')), Name)
di68kap's avatar
di68kap committed
91
92
    PI = Series(Token('<?'), PITarget, Option(Series(wsp__, PIChars)), Token('?>'))
    Comment = Series(Token('<!--'), ZeroOrMore(Alternative(CommentChars, RegExp('-(?!-)'))), Token('-->'))
eckhart's avatar
eckhart committed
93
94
95
96
97
98
99
    Misc = OneOrMore(Alternative(Comment, PI, S))
    NameChars = RegExp('(?x)(?:_|:|-|\\.|[A-Z]|[a-z]|[0-9]\n                   |\\u00B7|[\\u0300-\\u036F]|[\\u203F-\\u2040]\n                   |[\\u00C0-\\u00D6]|[\\u00D8-\\u00F6]|[\\u00F8-\\u02FF]\n                   |[\\u0370-\\u037D]|[\\u037F-\\u1FFF]|[\\u200C-\\u200D]\n                   |[\\u2070-\\u218F]|[\\u2C00-\\u2FEF]|[\\u3001-\\uD7FF]\n                   |[\\uF900-\\uFDCF]|[\\uFDF0-\\uFFFD]\n                   |[\\U00010000-\\U000EFFFF])+')
    NameStartChar = RegExp('(?x)_|:|[A-Z]|[a-z]\n                   |[\\u00C0-\\u00D6]|[\\u00D8-\\u00F6]|[\\u00F8-\\u02FF]\n                   |[\\u0370-\\u037D]|[\\u037F-\\u1FFF]|[\\u200C-\\u200D]\n                   |[\\u2070-\\u218F]|[\\u2C00-\\u2FEF]|[\\u3001-\\uD7FF]\n                   |[\\uF900-\\uFDCF]|[\\uFDF0-\\uFFFD]\n                   |[\\U00010000-\\U000EFFFF]')
    Name.set(Series(NameStartChar, Option(NameChars)))
    Names = Series(Name, ZeroOrMore(Series(RegExp(' '), Name)))
    Nmtoken = Synonym(NameChars)
    Nmtokens = Series(Nmtoken, ZeroOrMore(Series(RegExp(' '), Nmtoken)))
di68kap's avatar
di68kap committed
100
101
    PEReference = Series(Token('%'), Name, Token(';'))
    EntityRef = Series(Token('&'), Name, Token(';'))
eckhart's avatar
eckhart committed
102
    Reference = Alternative(EntityRef, CharRef)
di68kap's avatar
di68kap committed
103
104
105
106
    PubidLiteral = Alternative(Series(Token('"'), Option(PubidChars), Token('"')), Series(Token("'"), Option(PubidCharsSingleQuoted), Token("'")))
    SystemLiteral = Alternative(Series(Token('"'), RegExp('[^"]*'), Token('"')), Series(Token("'"), RegExp("[^']*"), Token("'")))
    AttValue = Alternative(Series(Token('"'), ZeroOrMore(Alternative(RegExp('[^<&"]+'), Reference)), Token('"')), Series(Token("'"), ZeroOrMore(Alternative(RegExp("[^<&']+"), Reference)), Token("'")))
    EntityValue = Alternative(Series(Token('"'), ZeroOrMore(Alternative(RegExp('[^%&"]+'), PEReference, Reference)), Token('"')), Series(Token("'"), ZeroOrMore(Alternative(RegExp("[^%&']+"), PEReference, Reference)), Token("'")))
eckhart's avatar
eckhart committed
107
    content = Series(Option(CharData), ZeroOrMore(Series(Alternative(element, Reference, CDSect, PI, Comment), Option(CharData))))
di68kap's avatar
di68kap committed
108
    Attribute = Series(Name, wsp__, Token('='), wsp__, AttValue, mandatory=2)
eckhart's avatar
eckhart committed
109
    TagName = Capture(Name)
di68kap's avatar
di68kap committed
110
111
112
    emptyElement = Series(Token('<'), Name, ZeroOrMore(Series(wsp__, Attribute)), wsp__, Token('/>'))
    ETag = Series(Token('</'), Pop(TagName), wsp__, Token('>'), mandatory=1)
    STag = Series(Token('<'), TagName, ZeroOrMore(Series(wsp__, Attribute)), wsp__, Token('>'))
eckhart's avatar
eckhart committed
113
    element.set(Alternative(emptyElement, Series(STag, content, ETag, mandatory=1)))
di68kap's avatar
di68kap committed
114
115
116
117
    NDataDecl = Series(Token('NData'), S, Name, mandatory=1)
    PublicID = Series(Token('PUBLIC'), S, PubidLiteral, mandatory=1)
    ExternalID = Series(Token('SYSTEM'), S, SystemLiteral, mandatory=1)
    NotationDecl = Series(Token('<!NOTATION'), S, Name, wsp__, Alternative(ExternalID, PublicID), wsp__, Token('>'), mandatory=1)
eckhart's avatar
eckhart committed
118
119
    PEDef = Alternative(EntityValue, ExternalID)
    EntityDef = Alternative(EntityValue, Series(ExternalID, Option(NDataDecl)))
di68kap's avatar
di68kap committed
120
121
    PEDecl = Series(Token('<!ENTITY'), S, Token('%'), S, Name, S, PEDef, wsp__, Token('>'), mandatory=3)
    GEDecl = Series(Token('<!ENTITY'), S, Name, S, EntityDef, wsp__, Token('>'), mandatory=3)
eckhart's avatar
eckhart committed
122
    EntityDecl = Alternative(GEDecl, PEDecl)
di68kap's avatar
di68kap committed
123
124
125
    FIXED = Series(Option(Series(Token('#FIXED'), S)), AttValue)
    IMPLIED = Token('#IMPLIED')
    REQUIRED = Token('#REQUIRED')
eckhart's avatar
eckhart committed
126
    DefaultDecl = Alternative(REQUIRED, IMPLIED, FIXED)
di68kap's avatar
di68kap committed
127
128
    Enumeration = Series(Token('('), wsp__, Nmtoken, ZeroOrMore(Series(wsp__, Token('|'), wsp__, Nmtoken)), wsp__, Token(')'))
    NotationType = Series(Token('NOTATION'), S, Token('('), wsp__, Name, ZeroOrMore(Series(wsp__, Token('|'), wsp__, Name)), wsp__, Token(')'))
eckhart's avatar
eckhart committed
129
    EnumeratedType = Alternative(NotationType, Enumeration)
di68kap's avatar
di68kap committed
130
131
132
133
134
135
136
    NMTOKENS = Token('NMTOKENS')
    NMTOKEN = Token('NMTOKEN')
    ENTITIES = Token('ENTITIES')
    ENTITY = Token('ENTITY')
    IDREFS = Token('IDREFS')
    IDREF = Token('IDREF')
    ID = Token('ID')
eckhart's avatar
eckhart committed
137
    TokenizedType = Alternative(ID, IDREF, IDREFS, ENTITY, ENTITIES, NMTOKEN, NMTOKENS)
di68kap's avatar
di68kap committed
138
    StringType = Token('CDATA')
eckhart's avatar
eckhart committed
139
    AttType = Alternative(StringType, TokenizedType, EnumeratedType)
di68kap's avatar
di68kap committed
140
141
142
143
144
145
146
147
148
    AttDef = Series(Name, wsp__, AttType, S, DefaultDecl, mandatory=2)
    AttlistDecl = Series(Token('<!ATTLIST'), S, Name, ZeroOrMore(Series(wsp__, AttDef)), wsp__, Token('>'), mandatory=1)
    seq = Series(Token('('), wsp__, cp, ZeroOrMore(Series(wsp__, Token(','), wsp__, cp)), wsp__, Token(')'))
    cp.set(Series(Alternative(Name, choice, seq), Option(Alternative(Token('?'), Token('*'), Token('+')))))
    choice.set(Series(Token('('), wsp__, OneOrMore(Series(wsp__, Token('|'), wsp__, cp)), wsp__, Token(')')))
    children = Series(Alternative(choice, seq), Option(Alternative(Token('?'), Token('*'), Token('+'))))
    Mixed = Alternative(Series(Token('('), wsp__, Token('#PCDATA'), ZeroOrMore(Series(wsp__, Token('|'), wsp__, Name)), wsp__, Token(')*')), Series(Token('('), wsp__, Token('#PCDATA'), wsp__, Token(')')))
    ANY = Token('ANY')
    EMPTY = Token('EMPTY')
eckhart's avatar
eckhart committed
149
    contentspec = Alternative(EMPTY, ANY, Mixed, children)
di68kap's avatar
di68kap committed
150
151
    elementdecl = Series(Token('<!ELEMENT'), S, Name, wsp__, contentspec, wsp__, Token('>'), mandatory=1)
    TextDecl = Series(Token('<?xml'), Option(VersionInfo), EncodingDecl, wsp__, Token('?>'))
eckhart's avatar
eckhart committed
152
    extParsedEnt = Series(Option(TextDecl), content)
di68kap's avatar
di68kap committed
153
154
155
    ignoreSectContents.set(Series(IgnoreChars, ZeroOrMore(Series(Token('<!['), ignoreSectContents, Token(']]>'), IgnoreChars))))
    ignoreSect = Series(Token('<!['), wsp__, Token('IGNORE'), wsp__, Token('['), ignoreSectContents, Token(']]>'))
    includeSect = Series(Token('<!['), wsp__, Token('INCLUDE'), wsp__, Token('['), extSubsetDecl, Token(']]>'))
eckhart's avatar
eckhart committed
156
157
158
159
160
161
    conditionalSect = Alternative(includeSect, ignoreSect)
    extSubsetDecl.set(ZeroOrMore(Alternative(markupdecl, conditionalSect, DeclSep)))
    extSubset = Series(Option(TextDecl), extSubsetDecl)
    markupdecl.set(Alternative(elementdecl, AttlistDecl, EntityDecl, NotationDecl, PI, Comment))
    DeclSep.set(Alternative(PEReference, S))
    intSubset = ZeroOrMore(Alternative(markupdecl, DeclSep))
di68kap's avatar
di68kap committed
162
163
164
165
    doctypedecl = Series(Token('<!DOCTYPE'), wsp__, Name, Option(Series(wsp__, ExternalID)), wsp__, Option(Series(Token('['), intSubset, Token(']'), wsp__)), Token('>'))
    No = Token('no')
    Yes = Token('yes')
    SDDecl = Series(wsp__, Token('standalone'), wsp__, Token('='), wsp__, Alternative(Alternative(Series(Token("'"), Yes), Series(No, Token("'"))), Alternative(Series(Token('"'), Yes), Series(No, Token('"')))))
eckhart's avatar
eckhart committed
166
    EncName = RegExp('[A-Za-z][A-Za-z0-9._\\-]*')
di68kap's avatar
di68kap committed
167
    EncodingDecl.set(Series(wsp__, Token('encoding'), wsp__, Token('='), wsp__, Alternative(Series(Token("'"), EncName, Token("'")), Series(Token('"'), EncName, Token('"')))))
eckhart's avatar
eckhart committed
168
    VersionNum = RegExp('[0-9]+\\.[0-9]+')
di68kap's avatar
di68kap committed
169
170
171
    VersionInfo.set(Series(wsp__, Token('version'), wsp__, Token('='), wsp__, Alternative(Series(Token("'"), VersionNum, Token("'")), Series(Token('"'), VersionNum, Token('"')))))
    XMLDecl = Series(Token('<?xml'), VersionInfo, Option(EncodingDecl), Option(SDDecl), wsp__, Token('?>'))
    prolog = Series(Option(Series(wsp__, XMLDecl)), Option(Misc), Option(Series(doctypedecl, Option(Misc))))
eckhart's avatar
eckhart committed
172
173
174
175
    document = Series(prolog, element, Option(Misc), EOF)
    root__ = document
    
def get_grammar() -> XMLGrammar:
176
    global GLOBALS
eckhart's avatar
eckhart committed
177
    try:
178
179
180
181
182
183
        grammar = GLOBALS.XML_1_grammar_singleton
    except AttributeError:
        GLOBALS.XML_1_grammar_singleton = XMLGrammar()
        if hasattr(get_grammar, 'python_src__'):
            GLOBALS.XML_1_grammar_singleton.python_src__ = get_grammar.python_src__
        grammar = GLOBALS.XML_1_grammar_singleton
eckhart's avatar
eckhart committed
184
185
186
187
188
189
190
191
192
193
194
195
    return grammar


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


XML_AST_transformation_table = {
    # AST Transformations for the XML-grammar
196
    "<": [remove_empty, remove_anonymous_tokens, remove_whitespace, remove_nodes("S")],
eckhart's avatar
eckhart committed
197
    "document": [flatten(lambda context: context[-1].tag_name == 'prolog', recursive=False)],
eckhart's avatar
eckhart committed
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
    "prolog": [],
    "XMLDecl": [],
    "VersionInfo": [reduce_single_child],
    "VersionNum": [],
    "EncodingDecl": [reduce_single_child],
    "EncName": [],
    "SDDecl": [],
    "Yes": [],
    "No": [],
    "doctypedecl": [],
    "intSubset": [],
    "DeclSep": [replace_or_reduce],
    "markupdecl": [replace_or_reduce],
    "extSubset": [],
    "extSubsetDecl": [],
    "conditionalSect": [replace_or_reduce],
    "includeSect": [],
    "ignoreSect": [],
    "ignoreSectContents": [],
    "extParsedEnt": [],
    "TextDecl": [],
    "elementdecl": [],
    "contentspec": [replace_or_reduce],
    "EMPTY": [],
    "ANY": [],
    "Mixed": [replace_or_reduce],
    "children": [],
    "choice": [],
    "cp": [],
    "seq": [],
    "AttlistDecl": [],
    "AttDef": [],
    "AttType": [replace_or_reduce],
    "StringType": [],
    "TokenizedType": [replace_or_reduce],
    "ID": [],
    "IDREF": [],
    "IDREFS": [],
    "ENTITY": [],
    "ENTITIES": [],
    "NMTOKEN": [],
    "NMTOKENS": [],
    "EnumeratedType": [replace_or_reduce],
    "NotationType": [],
    "Enumeration": [],
    "DefaultDecl": [replace_or_reduce],
    "REQUIRED": [],
    "IMPLIED": [],
    "FIXED": [],
    "EntityDecl": [replace_or_reduce],
    "GEDecl": [],
    "PEDecl": [],
    "EntityDef": [replace_or_reduce],
    "PEDef": [replace_or_reduce],
    "NotationDecl": [],
    "ExternalID": [],
    "PublicID": [],
    "NDataDecl": [],
    "element": [flatten, replace_by_single_child],
    "STag": [],
    "ETag": [reduce_single_child],
    "emptyElement": [],
    "TagName": [replace_by_single_child],
    "Attribute": [],
    "content": [flatten],
    "EntityValue": [replace_or_reduce],
    "AttValue": [replace_or_reduce],
    "SystemLiteral": [replace_or_reduce],
    "PubidLiteral": [replace_or_reduce],
    "Reference": [replace_or_reduce],
    "EntityRef": [],
    "PEReference": [],
    "Nmtokens": [],
    "Nmtoken": [reduce_single_child],
    "Names": [],
    "Name": [collapse],
    "NameStartChar": [],
    "NameChars": [],
    "Misc": [],
    "Comment": [],
    "PI": [],
    "PITarget": [reduce_single_child],
    "CDSect": [],
    "PubidCharsSingleQuoted": [],
    "PubidChars": [],
    "CharData": [],
    "CData": [],
    "IgnoreChars": [],
    "PIChars": [],
    "CommentChars": [],
    "CharRef": [replace_or_reduce],
    "Chars": [],
    "Char": [],
    "S": [],
    "EOF": [],
293
    ":_Token, :_RE": reduce_single_child,
eckhart's avatar
eckhart committed
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
    "*": replace_by_single_child
}


def XMLTransform() -> TransformationDict:
    return partial(traverse, processing_table=XML_AST_transformation_table.copy())


def get_transformer() -> TransformationFunc:
    global thread_local_XML_transformer_singleton
    try:
        transformer = thread_local_XML_transformer_singleton
    except NameError:
        thread_local_XML_transformer_singleton = XMLTransform()
        transformer = thread_local_XML_transformer_singleton
    return transformer


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

# def internalize(context):
#     """Sets the node's parser type to the tag name and internalizes
320
#     XML attr."""
eckhart's avatar
eckhart committed
321
322
323
324
325
326
327
328
329
#     node = context[-1]
#     if node.parser.name == 'element':
#         node.parser = MockParser(node['STag']['Name'].content, ':element')
#         node.result = node.result[1:-1]
#     elif node.parser.name == 'emptyElement':
#         node.parser = MockParser(node['Name'].content, ':emptyElement')
#         node.result = node.result[1:]
#     else:
#         assert node.parser.ptype in [':element', ':emptyElement'], \
330
#             "Tried to internalize tag name and attr for non element component!"
eckhart's avatar
eckhart committed
331
332
333
#         return
#     for nd in node.result:
#         if nd.parser.name == 'Attribute':
334
#             node.attr[nd['Name'].content] = nd['AttValue'].content
eckhart's avatar
eckhart committed
335
336
337
338
339
340
341
#     remove_nodes(context, {'Attribute'})


class XMLCompiler(Compiler):
    """Compiler for the abstract-syntax-tree of a XML source file.
    """

eckhart's avatar
eckhart committed
342
343
    def __init__(self):
        super(XMLCompiler, self).__init__()
eckhart's avatar
eckhart committed
344
        self.cleanup_whitespace = True  # remove empty CharData from mixed elements
eckhart's avatar
eckhart committed
345
346
347

    def _reset(self):
        super()._reset()
Eckhart Arnold's avatar
Eckhart Arnold committed
348
349
350
351
352
353
        self.mock_parsers = dict()

    def extract_attributes(self, node_sequence):
        attributes = OrderedDict()
        for node in node_sequence:
            if node.tag_name == "Attribute":
354
355
                assert node[0].tag_name == "Name", node.as_sexpr()
                assert node[1].tag_name == "AttValue", node.as_sxpr()
Eckhart Arnold's avatar
Eckhart Arnold committed
356
357
358
359
360
361
362
                attributes[node[0].content] = node[1].content
        return attributes

    def get_parser(self, tag_name):
        """Returns a mock parser with the given tag_name as parser name."""
        return self.mock_parsers.setdefault(tag_name, MockParser(tag_name))

eckhart's avatar
eckhart committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    def validity_constraint(self, node, condition, err_msg):
        """If `condition` is False an error is issued."""
        if not condition:
            self.tree.add_error(node, err_msg)

    def value_constraint(self, node, value, allowed):
        """If value is not in allowed, an error is issued."""
        self.constraint(node, value in allowed,
            'Invalid value "%s" for "standalone"! Must be one of %s.' % (value, str(allowed)))

    def on_document(self, node):
        self.tree.omit_tags.update({'CharData', 'document'})
        # TODO: Remove the following line. It is specific for testing with example.xml!
        self.tree.inline_tags.update({'to', 'from', 'heading', 'body', 'remark'})
        return self.fallback_compiler(node)

eckhart's avatar
eckhart committed
379
380
381
    # def on_prolog(self, node):
    #     return node

eckhart's avatar
eckhart committed
382
383
384
385
386
387
388
389
390
391
392
393
    def on_XMLDecl(self, node):
        attributes = dict()
        for child in node.children:
            s = child.content
            if child.tag_name == "VersionInfo":
                attributes['version'] = s
            elif child.tag_name == "EncodingDecl":
                attributes['encoding'] = s
            elif child.tag_name == "SDDecl":
                attributes['standalone'] = s
                self.value_constraint(node, s, {'yes', 'no'})
        if attributes:
394
            node.attr.update(attributes)
eckhart's avatar
eckhart committed
395
396
        node.result = ''
        self.tree.empty_tags.add('?xml')
397
        node.tag_name = '?xml'  # node.parser = self.get_parser('?xml')
eckhart's avatar
eckhart committed
398
        return node
eckhart's avatar
eckhart committed
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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Eckhart Arnold's avatar
Eckhart Arnold committed
568
569
    def on_element(self, node):
        stag = node['STag']
eckhart's avatar
eckhart committed
570
        tag_name = stag['Name'].content
Eckhart Arnold's avatar
Eckhart Arnold committed
571
        attributes = self.extract_attributes(stag.children)
eckhart's avatar
eckhart committed
572
        preserve_whitespace = tag_name in self.tree.inline_tags
Eckhart Arnold's avatar
Eckhart Arnold committed
573
        if attributes:
574
            node.attr.update(attributes)
eckhart's avatar
eckhart committed
575
            preserve_whitespace |= attributes.get('xml:space', '') == 'preserve'
di68kap's avatar
di68kap committed
576
        node.tag_name = tag_name
577
        content = self.compile_children(node.get('content', PLACEHOLDER))
eckhart's avatar
eckhart committed
578
579
580
581
582
583
584
585
586
        if len(content) == 1:
            if content[0].tag_name == "CharData":
                # reduce single CharData children
                content = content[0].content
        elif self.cleanup_whitespace and not preserve_whitespace:
            # remove CharData that consists only of whitespace from mixed elements
            content = tuple(child for child in content
                            if child.tag_name != "CharData" or child.content.strip() != '')
        node.result = content
Eckhart Arnold's avatar
Eckhart Arnold committed
587
        return node
eckhart's avatar
eckhart committed
588
589
590
591
592
593
594

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

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

Eckhart Arnold's avatar
Eckhart Arnold committed
595
596
597
    def on_emptyElement(self, node):
        attributes = self.extract_attributes(node.children)
        if attributes:
598
            node.attr.update(attributes)
599
        node.tag_name = node['Name'].content  # node.parser = self.get_parser(node['Name'].content)
Eckhart Arnold's avatar
Eckhart Arnold committed
600
        node.result = ''
601
        self.tree.empty_tags.add(node.tag_name)
Eckhart Arnold's avatar
Eckhart Arnold committed
602
        return node
eckhart's avatar
eckhart committed
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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


eckhart's avatar
eckhart committed
704
def get_compiler() -> XMLCompiler:
eckhart's avatar
eckhart committed
705
706
707
708
    global thread_local_XML_compiler_singleton
    try:
        compiler = thread_local_XML_compiler_singleton
    except NameError:
eckhart's avatar
eckhart committed
709
        thread_local_XML_compiler_singleton = XMLCompiler()
eckhart's avatar
eckhart committed
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
        compiler = thread_local_XML_compiler_singleton
    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__
        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:
        try:
            grammar_file_name = os.path.basename(__file__).replace('Compiler.py', '.ebnf')
            if grammar_changed(XMLGrammar, grammar_file_name):
                print("Grammar has changed. Please recompile Grammar first.")
                sys.exit(1)
        except FileNotFoundError:
            print('Could not check for changed grammar, because grammar file "%s" was not found!'
                  % grammar_file_name)    
        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:
eckhart's avatar
eckhart committed
756
            print(result.as_sxpr(compact=True))
757
            print(result.customized_XML() if isinstance(result, Node) else result)
eckhart's avatar
eckhart committed
758
759
    else:
        print("Usage: XMLCompiler.py [FILENAME]")