LaTeXCompiler.py 11 KB
Newer Older
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
#!/usr/bin/python

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


from functools import partial
import os
import sys
try:
    import regex as re
except ImportError:
    import re
from DHParser.toolkit import logging, is_filename, load_if_file    
from DHParser.parsers import Grammar, Compiler, nil_scanner, \
    Lookbehind, Lookahead, Alternative, Pop, Required, Token, Synonym, \
    Optional, NegativeLookbehind, OneOrMore, RegExp, Retrieve, Series, RE, Capture, \
    ZeroOrMore, Forward, NegativeLookahead, mixin_comment, compile_source, \
    last_value, counterpart, accumulate, ScannerFunc
from DHParser.syntaxtree import Node, traverse, remove_brackets, keep_children, \
    remove_children_if, reduce_single_child, replace_by_single_child, remove_whitespace, \
    remove_expendables, remove_tokens, flatten, is_whitespace, is_expendable, join, \
    collapse, replace_content, WHITESPACE_PTYPE, TOKEN_PTYPE, TransformationFunc, \
    remove_empty, replace_parser, apply_if


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

def LaTeXScanner(text):
    return text

def get_scanner() -> ScannerFunc:
    return LaTeXScanner


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

class LaTeXGrammar(Grammar):
    r"""Parser for a LaTeX source file, with this grammar:
    
    # latex Grammar
    
    @ testing    = True
    @ whitespace = /[ \t]*(?:\n(?![ \t]*\n)[ \t]*)?/    # optional whitespace, including at most one linefeed
    @ comment    = /%.*(?:\n|$)/
    
    latexdoc   = preamble document
    preamble   = { command }+
    
    document   = [PARSEP] { [PARSEP] paragraph } §EOF
    
    blockenv   = beginenv sequence §endenv
    
    parblock   = "{" sequence §"}"
    
    sequence   = { paragraph [PARSEP] }+
    paragraph  = { !blockcmd (command | block | text) //~ }+
    
    inlineenv  = beginenv { command | block | text }+ endenv
    beginenv   = "\begin{" §NAME §"}"
    endenv     = "\end{" §::NAME §"}"
    
    command    = CMDNAME [[ //~ config ] //~ block ]
    config     = "[" cfgtext §"]"
    block      = /{/ { command | text | block } §/}/
    
    text       = { cfgtext | (BRACKETS //~) }+
    cfgtext    = { word_sequence | (ESCAPED //~) }+
    word_sequence = { TEXTCHUNK //~ }+
    
    blockcmd   = "\subsection" | "\section" | "\chapter" | "\subsubsection"
                 | "\paragraph" | "\subparagraph" | "\begin{enumerate}"
                 | "\begin{itemize}" | "\item" | "\begin{figure}"
    
    CMDNAME    = /\\(?:(?!_)\w)+/~
    NAME       = /\w+/~
    
    ESCAPED    = /\\[%$&_\/]/
    BRACKETS   = /[\[\]]/                       # left or right square bracket: [ ]
    TEXTCHUNK  = /[^\\%$&\{\}\[\]\s\n]+/        # some piece of text excluding whitespace,
                                                # linefeed and special characters
    WSPC       = /[ \t]+/                       # (horizontal) whitespace
    LF         = !PARSEP /[ \t]*\n[ \t]*/       # LF but not an empty line
    PARSEP     = /[ \t]*(?:\n[ \t]*)+\n[ \t]*/  # at least one empty line, i.e.
                                                # [whitespace] linefeed [whitespace] linefeed
    
    EOF        = !/./
    """
    block = Forward()
    command = Forward()
    source_hash__ = "936e76e84dd027b0af532abfad617d15"
    parser_initialization__ = "upon instantiation"
    COMMENT__ = r'%.*(?:\n|$)'
    WSP__ = mixin_comment(whitespace=r'[ \t]*(?:\n(?![ \t]*\n)[ \t]*)?', comment=r'%.*(?:\n|$)')
    wspL__ = ''
    wspR__ = WSP__
    EOF = NegativeLookahead(RE('.', wR=''))
    PARSEP = RE('[ \\t]*(?:\\n[ \\t]*)+\\n[ \\t]*', wR='')
    LF = Series(NegativeLookahead(PARSEP), RE('[ \\t]*\\n[ \\t]*', wR=''))
    WSPC = RE('[ \\t]+', wR='')
    TEXTCHUNK = RE('[^\\\\%$&\\{\\}\\[\\]\\s\\n]+', wR='')
    BRACKETS = RE('[\\[\\]]', wR='')
    ESCAPED = RE('\\\\[%$&_/]', wR='')
    NAME = Capture(RE('\\w+'))
    CMDNAME = RE('\\\\(?:(?!_)\\w)+')
    blockcmd = Alternative(Token("\\subsection"), Token("\\section"), Token("\\chapter"), Token("\\subsubsection"), Token("\\paragraph"), Token("\\subparagraph"), Token("\\begin{enumerate}"), Token("\\begin{itemize}"), Token("\\item"), Token("\\begin{figure}"))
    word_sequence = OneOrMore(Series(TEXTCHUNK, RE('')))
    cfgtext = OneOrMore(Alternative(word_sequence, Series(ESCAPED, RE(''))))
    text = OneOrMore(Alternative(cfgtext, Series(BRACKETS, RE(''))))
    block.set(Series(RE('{', wR=''), ZeroOrMore(Alternative(command, text, block)), Required(RE('}', wR=''))))
    config = Series(Token("["), cfgtext, Required(Token("]")))
    command.set(Series(CMDNAME, Optional(Series(Optional(Series(RE(''), config)), RE(''), block))))
    endenv = Series(Token("\\end{"), Required(Pop(NAME)), Required(Token("}")))
    beginenv = Series(Token("\\begin{"), Required(NAME), Required(Token("}")))
    inlineenv = Series(beginenv, OneOrMore(Alternative(command, block, text)), endenv)
    paragraph = OneOrMore(Series(NegativeLookahead(blockcmd), Alternative(command, block, text), RE('')))
    sequence = OneOrMore(Series(paragraph, Optional(PARSEP)))
    parblock = Series(Token("{"), sequence, Required(Token("}")))
    blockenv = Series(beginenv, sequence, Required(endenv))
    document = Series(Optional(PARSEP), ZeroOrMore(Series(Optional(PARSEP), paragraph)), Required(EOF))
    preamble = OneOrMore(command)
    latexdoc = Series(preamble, document)
    root__ = latexdoc
    
def get_grammar() -> LaTeXGrammar:
    global thread_local_LaTeX_grammar_singleton
    try:
        grammar = thread_local_LaTeX_grammar_singleton
        return grammar
    except NameError:
        thread_local_LaTeX_grammar_singleton = LaTeXGrammar()
        return thread_local_LaTeX_grammar_singleton


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


def streamline_whitespace(node):
    assert node.tag_name in ['WSPC', ':Whitespace']
    s = str(node)
    c = s.find('%')
    n = s.find('\n')
    if c >= 0:
        node.result = ('  ' if (n >= c) or (n < 0) else '\n')+ s[c:].rstrip(' \t')
    elif s.find('\n') >= 0:
        node.result = '\n'
    else:
        node.result = ' '


LaTeX_AST_transformation_table = {
    # AST Transformations for the LaTeX-grammar
    "+":
        remove_empty,
    "latexdoc": [],
    "preamble": [],
    "document": [],
    "blockenv": [],
    "parblock": [],
    "sequence":
        flatten,
    "paragraph":
        [flatten(lambda node: not node.parser.name or node.parser.name == "text"),
         join('text', ':Whitespace')],
    "inlineenv": [],
    "beginenv": [],
    "endenv": [],
    "command": [],
    "config": [],
    "block": [remove_brackets, reduce_single_child],
    "text":
        [reduce_single_child, join('text', 'word_sequence', ':Whitespace')],
    "cfgtext": [flatten, reduce_single_child],
    "word_sequence":
        [collapse],
    "blockcmd": [],
    "CMDNAME":
        [remove_expendables, reduce_single_child],
    "NAME": [],
    "ESCAPED": [reduce_single_child],
    "BRACKETS": [],
    "TEXTCHUNK": [],
    "WSPC, :Whitespace":
        streamline_whitespace,
    "LF":
        replace_content(lambda node: '\n'),
    "PARSEP":
        replace_content(lambda node: '\n\n'),
    "EOF": [],
    "*":
        replace_by_single_child,
}

LaTeXTransform = partial(traverse, processing_table=LaTeX_AST_transformation_table)
# LaTeXTransform = lambda tree : 1

def get_transformer() -> TransformationFunc:
    return LaTeXTransform


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

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

    def __init__(self, grammar_name="LaTeX", grammar_source=""):
        super(LaTeXCompiler, self).__init__(grammar_name, grammar_source)
        assert re.match('\w+\Z', grammar_name)

    def on_latexdoc(self, node):
        return node.as_sexpr()

    def on_preamble(self, node):
        pass

    def on_document(self, node):
        pass

    def on_blockenv(self, node):
        pass

    def on_parblock(self, node):
        pass

    def on_sequence(self, node):
        pass

    def on_paragraph(self, node):
        pass

    def on_inlineenv(self, node):
        pass

    def on_beginenv(self, node):
        pass

    def on_endenv(self, node):
        pass

    def on_command(self, node):
        pass

    def on_config(self, node):
        pass

    def on_block(self, node):
        pass

    def on_text(self, node):
        pass

    def on_cfgtext(self, node):
        pass

    def on_word_sequence(self, node):
        pass

    def on_blockcmd(self, node):
        pass

    def on_CMDNAME(self, node):
        pass

    def on_NAME(self, node):
        pass

    def on_ESCAPED(self, node):
        pass

    def on_BRACKETS(self, node):
        pass

    def on_TEXTCHUNK(self, node):
        pass

    def on_WSPC(self, node):
        pass

    def on_LF(self, node):
        pass

    def on_PARSEP(self, node):
        pass

    def on_EOF(self, node):
        pass


def get_compiler(grammar_name="LaTeX", grammar_source="") -> LaTeXCompiler:
    global thread_local_LaTeX_compiler_singleton
    try:
        compiler = thread_local_LaTeX_compiler_singleton
        compiler.set_grammar_name(grammar_name, grammar_source)
        return compiler
    except NameError:
        thread_local_LaTeX_compiler_singleton = \
            LaTeXCompiler(grammar_name, grammar_source)
        return thread_local_LaTeX_compiler_singleton 


#######################################################################
#
# 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_scanner(), 
                                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:
            print(result)
    else:
        print("Usage: LaTeXCompiler.py [FILENAME]")