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

dhparser.py 8.27 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 import compile_source
29
from DHParser.log import logging
30

31
EBNF_TEMPLATE = r"""-grammar
32

33 34 35 36 37 38
#######################################################################
#
#  EBNF-Directives
#
#######################################################################

39
@ whitespace  = vertical        # implicit whitespace, includes any number of line feeds
40
@ literalws   = right           # literals have implicit whitespace on the right hand side
Eckhart Arnold's avatar
Eckhart Arnold committed
41
@ comment     = /#.*/           # comments range from a '#'-character to the end of the line
42 43 44 45 46 47 48 49 50
@ ignorecase  = False           # literals and regular expressions are case-sensitive


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

51
document = //~ { WORD } §EOF    # root parser: a sequence of words preceded by whitespace
52 53 54 55 56 57 58 59
                                # until the end of file

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

60 61
WORD     =  /\w+/~      # a sequence of letters, optional trailing whitespace
EOF      =  !/./        # no more characters ahead, end of file reached
62 63
"""

64
TEST_WORD_TEMPLATE = r'''[match:WORD]
65 66
M1: word
M2: one_word_with_underscores
67 68

[fail:WORD]
69
F1: two words
70 71 72
'''

TEST_DOCUMENT_TEMPLATE = r'''[match:document]
73 74 75
M1: """This is a sequence of words
    extending over several lines"""

76
[fail:document]
77 78
F1: """This test should fail, because neither
    comma nor full have been defined anywhere."""
79
'''
80 81 82 83 84 85 86 87 88 89

README_TEMPLATE = """# {name}

PLACE A SHORT DESCRIPTION HERE

Author: AUTHOR'S NAME <EMAIL>, AFFILIATION


## License

90
{name} is open source software under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0)
91 92 93

Copyright YEAR AUTHOR'S NAME <EMAIL>, AFFILIATION

94 95 96 97 98 99 100 101 102 103 104
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

    https://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.
105 106 107
"""


108
GRAMMAR_TEST_TEMPLATE = r'''#!/usr/bin/python3
109 110 111 112 113 114 115 116 117 118

"""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

119 120
# recompiles Grammar only if it has changed
if not DHParser.dsl.recompile_grammar('{name}.ebnf', force=False):
121 122 123 124 125 126
    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('./')
127 128
# must be appended after module creation, because
# otherwise an ImportError is raised under Windows
129 130 131 132 133 134 135 136 137 138
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:
139
    print('ready.')
140
'''
141 142


143 144 145
def create_project(path: str):
    """Creates the a new DHParser-project in the given `path`.
    """
146
    def create_file(name, content):
147
        """Create a file with `name` and write `content` to file."""
148 149 150 151 152 153 154 155
        if not os.path.exists(name):
            print('Creating file "%s".' % name)
            with open(name, 'w') as f:
                f.write(content)
        else:
            print('"%s" already exists! Not overwritten.' % name)

    if os.path.exists(path) and not os.path.isdir(path):
156
        print('Cannot create new project, because a file named "%s" already exists!' % path)
157 158
        sys.exit(1)
    name = os.path.basename(path)
159 160 161 162
    print('Creating new DHParser-project "%s".' % name)
    if not os.path.exists(path):
        os.mkdir(path)
    curr_dir = os.getcwd()
163
    os.chdir(path)
164 165 166 167 168 169 170 171 172 173 174 175
    if os.path.exists('grammar_tests'):
        if not os.path.isdir('grammar_tests'):
            print('Cannot overwrite existing file "grammar_tests"')
            sys.exit(1)
    else:
        os.mkdir('grammar_tests')

    create_file(os.path.join('grammar_tests', '01_test_word.ini'), TEST_WORD_TEMPLATE)
    create_file(os.path.join('grammar_tests', '02_test_document.ini'), TEST_DOCUMENT_TEMPLATE)
    create_file(name + '.ebnf', '# ' + name + EBNF_TEMPLATE)
    create_file('README.md', README_TEMPLATE.format(name=name))
    create_file('tst_%s_grammar.py' % name, GRAMMAR_TEST_TEMPLATE.format(name=name))
176
    os.chmod('tst_%s_grammar.py' % name, 0o755)
177
    os.chdir(curr_dir)
178 179
    print('ready.')

180

Eckhart Arnold's avatar
Eckhart Arnold committed
181
def selftest() -> bool:
182 183
    """Run a simple self-text of DHParser.
    """
Eckhart Arnold's avatar
Eckhart Arnold committed
184 185 186 187 188 189
    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')
190 191
    generated_ebnf_parser, errors, _ = compile_source(
        ebnf_src, None,
Eckhart Arnold's avatar
Eckhart Arnold committed
192 193 194 195
        builtin_ebnf_parser, ebnf_transformer, ebnf_compiler)

    if errors:
        print("Selftest FAILED :-(")
196
        print("\n\n".join(str(err) for err in errors))
Eckhart Arnold's avatar
Eckhart Arnold committed
197 198
        return False
    print(generated_ebnf_parser)
199 200
    print("\n\nSTAGE 2: Selfhosting-test: "
          "Trying to compile EBNF-Grammar with generated parser...\n")
Eckhart Arnold's avatar
Eckhart Arnold committed
201 202 203 204 205 206 207 208
    selfhosted_ebnf_parser = compileDSL(ebnf_src, None, generated_ebnf_parser,
                                        ebnf_transformer, ebnf_compiler)
    ebnf_compiler.gen_transformer_skeleton()
    print(selfhosted_ebnf_parser)
    print("\n\n Selftest SUCCEEDED :-)\n\n")
    return True


209
def cpu_profile(func, repetitions=1):
210 211 212 213 214 215 216
    """Profile the function `func`.
    """
    import cProfile
    import pstats
    profile = cProfile.Profile()
    profile.enable()
    for _ in range(repetitions):
217 218 219
        success = func()
        if not success:
            break
220
    profile.disable()
221
    # after your program ends
222 223 224
    stats = pstats.Stats(profile)
    stats.strip_dirs()
    stats.sort_stats('time').print_stats(40)
225
    return success
226 227


228 229 230
def mem_profile(func):
    """Profile memory usage of `func`.
    """
231 232 233 234 235 236 237 238 239 240 241
    import tracemalloc
    tracemalloc.start()
    success = func()
    snapshot = tracemalloc.take_snapshot()
    top_stats = snapshot.statistics('lineno')
    print("[ Top 20 ]")
    for stat in top_stats[:20]:
        print(stat)
    return success


242 243 244 245
def main():
    """Creates a project (if a project name has been passed as command line
    parameter) or runs a quick self-test.
    """
246
    if len(sys.argv) > 1:
247
        if os.path.exists(sys.argv[1]) and os.path.isfile(sys.argv[1]):
248 249 250
            _errors = compile_on_disk(sys.argv[1],
                                      sys.argv[2] if len(sys.argv) > 2 else "")
            if _errors:
251
                print('\n\n'.join(str(err) for err in _errors))
252 253 254
                sys.exit(1)
        else:
            create_project(sys.argv[1])
255 256 257
    else:
        # run self test
        # selftest('EBNF/EBNF.ebnf')
258
        with logging(False):
259
            if not cpu_profile(selftest, 1):
260 261
                sys.exit(1)

262

263 264
if __name__ == "__main__":
    main()