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

"""test_preprocess.py - tests of the preprocessor-module of DHParser

Author: Eckhart Arnold <arnold@badw.de>

Copyright 2017 Bavarian Academy of Sciences and Humanities

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

22
import os
23
24
25
import platform
import shutil
import subprocess
eckhart's avatar
eckhart committed
26
import sys
27
import time
eckhart's avatar
eckhart committed
28

29
30
scriptpath = os.path.dirname(__file__) or '.'
sys.path.append(os.path.abspath(os.path.join(scriptpath, '..')))
31

32
33
from functools import partial

34
from DHParser.configuration import set_config_value
35
from DHParser.dsl import grammar_provider
36
from DHParser import compile_source
Eckhart Arnold's avatar
Eckhart Arnold committed
37
from DHParser.preprocess import make_token, tokenized_to_original_mapping, source_map, \
eckhart's avatar
eckhart committed
38
    BEGIN_TOKEN, END_TOKEN, TOKEN_DELIMITER, SourceMapFunc, SourceMap, chain_preprocessors, \
39
40
41
42
    strip_tokens, generate_find_include_func, preprocess_includes, IncludeInfo
from DHParser.toolkit import lstrip_docstring, typing, re
from DHParser.testing import TFFN
from typing import Tuple, Dict
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65


class TestMakeToken:
    def test_make_token1(self):
        tk = make_token("INDENTED_BLOCK", " " * 4)
        assert tk[0] == BEGIN_TOKEN
        assert tk[-1] == END_TOKEN
        d = tk.find(TOKEN_DELIMITER)
        assert 0 < d < len(tk) - 1
        assert tk[1:d] == "INDENTED_BLOCK"
        assert tk[d + 1:-1] == " " * 4

    def test_make_token2(self):
        tk = make_token("EMPTY_TOKEN")
        assert tk[0] == BEGIN_TOKEN
        assert tk[-1] == END_TOKEN
        d = tk.find(TOKEN_DELIMITER)
        assert 0 < d < len(tk) - 1
        assert tk[1:d] == "EMPTY_TOKEN"
        assert tk[d + 1:-1] == ""


class TestSourceMapping:
66
67
68
69
    code = "All persons are mortal AND Socrates is a person YIELDS Socrates is mortal"
    tokenized = code.replace('AND', make_token('CONJUNCTION', 'AND')) \
        .replace('YIELDS', make_token('IMPLICATION', 'YIELDS'))

70
71
72
73
74
75
76

    def test_tokenized_to_original_mapping(self):
        srcmap = tokenized_to_original_mapping(self.tokenized)
        positions, offsets = srcmap.positions, srcmap.offsets
        assert len(positions) == len(offsets)
        assert positions[0] == 0
        assert all(positions[i] < positions[i + 1] for i in range(len(positions) - 1))
77
78
        assert all(offsets[i] > offsets[i + 1] for i in range(len(offsets) - 2))
        assert offsets[-1] >= offsets[-2]
79
80
        assert self.tokenized.find('AND') == self.code.find('AND') + len('CONJUNCTION') + 2

di68kap's avatar
di68kap committed
81
82
83
84
85
86
87
88
89
90
    def test_bondary_cases(self):
        # position at the end of the file
        source = " "
        srcmap = tokenized_to_original_mapping(source)
        pos = source_map(1, srcmap)
        # empty file
        source =""
        srcmap = tokenized_to_original_mapping(source)
        pos = source_map(0, srcmap)

91

92
def preprocess_indentation(src: str, src_name: str) -> str:
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
    transformed = []
    indent_level = 0
    for line in src.split('\n'):
        indent = len(line) - len(line.lstrip()) if line.strip() else indent_level * 4
        assert indent % 4 == 0
        if indent > indent_level * 4:
            assert indent == (indent_level + 1) * 4, str(indent)  # indent must be 4 spaces
            indent_level += 1
            line = make_token('BEGIN_INDENT') + line
        elif indent <= (indent_level - 1) * 4:
            while indent <= (indent_level - 1) * 4:
                line = make_token('END_INDENT') + line
                indent_level -= 1
            assert indent == (indent_level + 1) * 4  # indent must be 4 spaces
        else:
            assert indent == indent_level * 4
        transformed.append(line)
    while indent_level > 0:
        transformed[-1] += make_token('END_INDENT')
        indent_level -= 1
    tokenized = '\n'.join(transformed)
    # print(prettyprint_tokenized(tokenized))
    return tokenized

117
118

def preprocess_comments(src: str, src_name: str) -> Tuple[str, SourceMapFunc]:
119
120
121
122
123
124
125
126
127
128
129
130
131
    lines = src.split('\n')
    positions, offsets = [0], [0]
    pos = 0
    for i, line in enumerate(lines):
        comment_pos = line.find('#')
        if comment_pos >= 0:
            pos += comment_pos
            lines[i] = line[:comment_pos]
            positions.append(pos - offsets[-1])
            offsets.append(offsets[-1] + len(line) - comment_pos)
        pos += len(lines[i])
    positions.append(pos)
    offsets.append(offsets[-1])
132
133
    return '\n'.join(lines), \
           partial(source_map, srcmap=SourceMap('FILE_NAME_DUMMY', positions, offsets))
134
135


136
class TestTokenParsing:
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
    ebnf = r"""
        @ tokens     = BEGIN_INDENT, END_INDENT
        @ whitespace = /[ \t]*/ 
        block       = { line | indentBlock }+
        line        = ~/[^\x1b\x1c\x1d\n]*\n/
        indentBlock = BEGIN_INDENT block END_INDENT
        """
    set_config_value('max_parser_dropouts', 3)
    grammar = grammar_provider(ebnf)()
    code = lstrip_docstring("""
        def func(x, y):
            if x > 0:         # a comment
                if y > 0:
                    print(x)  # another comment
                    print(y)
        """)
153
    tokenized = preprocess_indentation(code, 'no_uri')
154
    srcmap = tokenized_to_original_mapping(tokenized)
155

156
    def verify_mapping(self, teststr, orig_text, preprocessed_text, mapping):
Eckhart Arnold's avatar
Eckhart Arnold committed
157
158
        mapped_pos = preprocessed_text.find(teststr)
        assert mapped_pos >= 0
159
        file_name, original_pos = mapping(mapped_pos)
160
        # original_pos = source_map(mapped_pos, self.srcmap)
Eckhart Arnold's avatar
Eckhart Arnold committed
161
162
163
164
        assert orig_text[original_pos:original_pos + len(teststr)] == teststr, \
            '"%s" (%i) wrongly mapped onto "%s" (%i)' % \
            (teststr, mapped_pos, orig_text[original_pos:original_pos + len(teststr)], original_pos)

eckhart's avatar
eckhart committed
165
166
167
    def test_strip_tokens(self):
        assert self.code == strip_tokens(self.tokenized)

168
169
170
171
    def test_parse_tokenized(self):
        cst = self.grammar(self.tokenized)
        assert not cst.error_flag

172
    def test_source_mapping_1(self):
173
174
175
176
177
178
        mapping = partial(source_map, srcmap=self.srcmap)
        self.verify_mapping("def func", self.code, self.tokenized, mapping)
        self.verify_mapping("x > 0:", self.code, self.tokenized, mapping)
        self.verify_mapping("if y > 0:", self.code, self.tokenized, mapping)
        self.verify_mapping("print(x)", self.code, self.tokenized, mapping)
        self.verify_mapping("print(y)", self.code, self.tokenized, mapping)
Eckhart Arnold's avatar
Eckhart Arnold committed
179

180
181
182
183
    def test_source_mapping_2(self):
        previous_index = 0
        L = len(self.code)
        for mapped_index in range(len(self.tokenized)):
184
            _, index = source_map(mapped_index, self.srcmap)
185
186
187
188
            assert previous_index <= index <= L, \
                "%i <= %i <= %i violated" % (previous_index, index, L)
            previous_index = index

189
    def test_non_token_preprocessor(self):
190
        tokenized, mapping = preprocess_comments(self.code, 'no_uri')
191
192
193
194
195
196
197
        self.verify_mapping("def func", self.code, tokenized, mapping)
        self.verify_mapping("x > 0:", self.code, tokenized, mapping)
        self.verify_mapping("if y > 0:", self.code, tokenized, mapping)
        self.verify_mapping("print(x)", self.code, tokenized, mapping)
        self.verify_mapping("print(y)", self.code, tokenized, mapping)

    def test_chained_preprocessors(self):
198
        pchain = chain_preprocessors(preprocess_comments, preprocess_indentation)
199
        tokenized, mapping = pchain(self.code, 'no_uri')
200
201
202
203
204
205
        self.verify_mapping("def func", self.code, tokenized, mapping)
        self.verify_mapping("x > 0:", self.code, tokenized, mapping)
        self.verify_mapping("if y > 0:", self.code, tokenized, mapping)
        self.verify_mapping("print(x)", self.code, tokenized, mapping)
        self.verify_mapping("print(y)", self.code, tokenized, mapping)

eckhart's avatar
eckhart committed
206
207
    def test_error_position(self):
        orig_src = self.code.replace('#', '\x1b')
208
        prepr = chain_preprocessors(preprocess_comments, preprocess_indentation)
209
        self.grammar.max_parser_dropouts__ = 3
eckhart's avatar
eckhart committed
210
211
212
213
214
215
216
217
        result, messages, syntaxtree = compile_source(orig_src, prepr, self.grammar,
                                                      lambda i: i, lambda i: i)
        for err in messages:
            if self.code[err.orig_pos] == "#":
                break
        else:
            assert False, "wrong error positions"

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
class TestHelpers:
    def test_generate_find_include_func(self):
        rx = re.compile(r'include\((?P<name>[^)\n]*)\)')
        find = generate_find_include_func(rx)
        info = find('''321include(sub.txt)xyz''', 0)
        assert info == IncludeInfo(3, 16, 'sub.txt')


def system(s: str) -> int:
    # return os.system(s)
    return subprocess.call(s, shell=True)


class TestIncludes:
    def setup(self):
        self.cwd = os.getcwd()
        os.chdir(scriptpath)
        # avoid race-condition
        counter = 10
        while counter > 0:
            try:
                self.dirname = TFFN('test_preprocess_data')
                os.mkdir(TFFN('test_preprocess_data'))
                counter = 0
            except FileExistsError:
                time.sleep(1)
                counter -= 1
        os.chdir(os.path.join(scriptpath, self.dirname))

    def teardown(self):
        os.chdir(scriptpath)
        if os.path.exists(self.dirname) and os.path.isdir(self.dirname):
            shutil.rmtree(self.dirname)
        if os.path.exists(self.dirname) and not os.listdir(self.dirname):
            os.rmdir(self.dirname)
        os.chdir(self.cwd)


    def create_files(self, files: Dict[str, str]):
        for name, content in files.items():
            with open(name, 'w', encoding='utf-8') as f:
                f.write(content)

    def test_simple_include(self):
        def perform(main, sub):
            self.create_files({'main.txt': main, 'sub.txt': sub})
            find_func = generate_find_include_func(r'include\((?P<name>[^)\n]*)\)')
            text, mapping = preprocess_includes('main.txt', None, find_func)
            print(mapping)
            assert text == main.replace('include(sub.txt)', 'abc'), text
            for i in range(len(text)):
                name, k = mapping(i)
                print(i, k, name)
                txt = main if name == 'main.txt' else sub
                assert text[i] == txt[k], f'{i}: {text[i]} != {txt[k]} in {name}'

        perform('include(sub.txt)xyz', 'abc')
        perform('012include(sub.txt)xyz', 'abc')
        perform('012xyzinclude(sub.txt)', 'abc')
        perform('01include(sub.txt)2xyz', 'abc')

        perform('012include(sub.txt)xyzinclude(sub.txt)hij', 'abc')
        perform('012include(sub.txt)include(sub.txt)hij', 'abc')
        perform('include(sub.txt)include(sub.txt)hijinclude(sub.txt)', 'abc')


285
286
287
288
289
290
if __name__ == "__main__":
    # tp = TestTokenParsing()
    # tp.setup()
    from DHParser.testing import runner

    runner("", globals())