Currently job artifacts in CI/CD pipelines on LRZ GitLab never expire. Starting from Wed 26.1.2022 the default expiration time will be 30 days (GitLab default). Currently existing artifacts in already completed jobs will not be affected by the change. The latest artifacts for all jobs in the latest successful pipelines will be kept. More information: https://gitlab.lrz.de/help/user/admin_area/settings/continuous_integration.html#default-artifacts-expiration

dhparser.py 7.18 KB
Newer Older
1
#!/usr/bin/python
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

"""dhparser.py - command line tool for DHParser

Copyright 2016  by Eckhart Arnold (arnold@badw.de)
                Bavarian Academy of Sciences an Humanities (badw.de)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.  See the License for the specific language governing
permissions and limitations under the License.
"""

21
#  TODO: This is still a stub...
22

23
24
25
import os
import sys

26
from DHParser.dsl import compileDSL, compile_on_disk
Eckhart Arnold's avatar
Eckhart Arnold committed
27
from DHParser.ebnf import get_ebnf_grammar, get_ebnf_transformer, get_ebnf_compiler
28
from DHParser.parser import compile_source
29
from DHParser.toolkit import logging
30

31

32
EBNF_TEMPLATE = """# {name}-grammar
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
#######################################################################
#
#  EBNF-Directives
#
#######################################################################

@ testing     = True            # testing supresses error messages for unconnected symbols
@ whitespace  = horizontal      # implicit whitespace ends at the end of the line
@ literalws   = right           # literals have implicit whitespace on the right hand side 
@ comment     = /#.*(?:\n|$)/   # comments range from a '#'-character to the end of the line
@ ignorecase  = False           # literals and regular expressions are case-sensitive


#######################################################################
#
#  Structure and Components
#
#######################################################################

document = //~ { WORD } §EOF    # root parser: optional whitespace followed by a sequence of words
                                # until the end of file

#######################################################################
#
#  Regular Expressions
#
#######################################################################

WORD     =  /\w+/~              # a sequence of letters, possibly followed by implicit whitespace
EOF      =  !/./                # no more characters ahead, end of file reached
"""


README_TEMPLATE = """# {name}

PLACE A SHORT DESCRIPTION HERE

Author: AUTHOR'S NAME <EMAIL>, AFFILIATION


## License

{name} is open source software under the [MIT License](https://opensource.org/licenses/MIT)

Copyright YEAR AUTHOR'S NAME <EMAIL>, AFFILIATION

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
 to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""


GRAMMAR_TEST_TEMPLATE = '''#!/usr/bin/python3

"""tst_{name}_grammar.py - runs the unit tests for the {name}-grammar
"""

import sys

import DHParser.dsl
from DHParser import testing
from DHParser import toolkit

if not DHParser.dsl.recompile_grammar('{name}.ebnf', force=False):  # recompiles Grammar only if it has changed
    print('\nErrors while recompiling "{name}.ebnf":\n--------------------------------------\n\n')
    with open('{name}_ebnf_ERRORS.txt') as f:
        print(f.read())
    sys.exit(1)

sys.path.append('./')
# must be appended after module creation, because otherwise an ImportError is raised under Windows
from {name}Compiler import get_grammar, get_transformer

with toolkit.logging(True):
    error_report = testing.grammar_suite('grammar_tests', get_grammar,
                                         get_transformer, report=True, verbose=True)
if error_report:
    print('\n')
    print(error_report)
    sys.exit(1)
else:
    print('\nSUCCESS! All tests passed :-)')
'''
132
133
134
135
136
137
138
139
140
141
142
143


def selftest() -> bool:
    print("DHParser selftest...")
    print("\nSTAGE I:  Trying to compile EBNF-Grammar:\n")
    builtin_ebnf_parser = get_ebnf_grammar()
    ebnf_src = builtin_ebnf_parser.__doc__[builtin_ebnf_parser.__doc__.find('#'):]
    ebnf_transformer = get_ebnf_transformer()
    ebnf_compiler = get_ebnf_compiler('EBNF')
    generated_ebnf_parser, errors, ast = compile_source(ebnf_src, None,
        builtin_ebnf_parser, ebnf_transformer, ebnf_compiler)

144
    if errors:
145
146
147
148
149
150
151
        print("Selftest FAILED :-(")
        print("\n\n".join(errors))
        return False
    print(generated_ebnf_parser)
    print("\n\nSTAGE 2: Selfhosting-test: Trying to compile EBNF-Grammar with generated parser...\n")
    selfhosted_ebnf_parser = compileDSL(ebnf_src, None, generated_ebnf_parser,
                                        ebnf_transformer, ebnf_compiler)
152
    ebnf_compiler.gen_transformer_skeleton()
153
154
155
156
    print(selfhosted_ebnf_parser)
    print("\n\n Selftest SUCCEEDED :-)\n\n")
    return True

157

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def create_project(path,
                   ebnf_tmpl=EBNF_TEMPLATE,
                   readme_tmpl=README_TEMPLATE,
                   grammar_test_tmpl=GRAMMAR_TEST_TEMPLATE):
    if os._exists(path):
        print('Cannot create new DHParser-project, because path %s alread exists!' % path)
        sys.exit(1)
    name = os.path.basename(path)
    print('Creating new DHParser-project "%s"...' % name)
    os.mkdir(path)
    # curr_dir = os.getcwd()
    os.chdir(path)
    os.mkdir('grammar_tests')
    with open(name + '.ebnf', 'w') as f:
        f.write(EBNF_TEMPLATE.format(name=name))
    with open('README.md', 'w') as f:
        f.write(README_TEMPLATE.format(name=name))
    with open('tst_%s_grammar.py') as f:
        f.write(GRAMMAR_TEST_TEMPLATE.format(name=name))
    # os.chdir(curr_dir)
    print('ready.')

180
181

def profile(func):
182
    import cProfile, pstats
183
184
    pr = cProfile.Profile()
    pr.enable()
185
186
187
188
    for i in range(1):
        success = func()
        if not success:
            break
189
190
    pr.disable()
    # after your program ends
191
192
193
    st = pstats.Stats(pr)
    st.strip_dirs()
    st.sort_stats('time').print_stats(10)
194
    return success
195
196
197
198


if __name__ == "__main__":
    if len(sys.argv) > 1:
199
200
201
202
203
204
205
206
        if os.path.exists(sys.argv[1]):
            _errors = compile_on_disk(sys.argv[1],
                                      sys.argv[2] if len(sys.argv) > 2 else "")
            if _errors:
                print('\n\n'.join(_errors))
                sys.exit(1)
        else:
            create_project(sys.argv[1])
207
208
209
    else:
        # run self test
        # selftest('EBNF/EBNF.ebnf')
210
        with logging(False):
211
212
213
            if not profile(selftest):
                sys.exit(1)