test_preprocess.py 8.37 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
eckhart's avatar
eckhart committed
23
24
import sys

25
26
scriptpath = os.path.dirname(__file__) or '.'
sys.path.append(os.path.abspath(os.path.join(scriptpath, '..')))
27

28
29
from functools import partial

30
from DHParser.configuration import set_config_value
31
from DHParser.dsl import grammar_provider
32
from DHParser import compile_source
Eckhart Arnold's avatar
Eckhart Arnold committed
33
from DHParser.preprocess import make_token, tokenized_to_original_mapping, source_map, \
eckhart's avatar
eckhart committed
34
35
    BEGIN_TOKEN, END_TOKEN, TOKEN_DELIMITER, SourceMapFunc, SourceMap, chain_preprocessors, \
    strip_tokens
36
37
from DHParser.toolkit import lstrip_docstring, typing
from typing import Tuple
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60


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:
61
62
63
64
    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'))

65
66
67
68
69
70
71

    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))
72
73
        assert all(offsets[i] > offsets[i + 1] for i in range(len(offsets) - 2))
        assert offsets[-1] >= offsets[-2]
74
75
        assert self.tokenized.find('AND') == self.code.find('AND') + len('CONJUNCTION') + 2

di68kap's avatar
di68kap committed
76
77
78
79
80
81
82
83
84
85
    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)

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
def preprocess_indentation(src: str) -> str:
    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

def preprocess_comments(src: str) -> Tuple[str, SourceMapFunc]:
    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])
    return '\n'.join(lines), partial(source_map, srcmap=SourceMap(positions, offsets))


129
class TestTokenParsing:
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    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)
        """)
    tokenized = preprocess_indentation(code)
    srcmap = tokenized_to_original_mapping(tokenized)
148

149
    def verify_mapping(self, teststr, orig_text, preprocessed_text, mapping):
Eckhart Arnold's avatar
Eckhart Arnold committed
150
151
        mapped_pos = preprocessed_text.find(teststr)
        assert mapped_pos >= 0
152
153
        original_pos = mapping(mapped_pos)
        # original_pos = source_map(mapped_pos, self.srcmap)
Eckhart Arnold's avatar
Eckhart Arnold committed
154
155
156
157
        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
158
159
160
    def test_strip_tokens(self):
        assert self.code == strip_tokens(self.tokenized)

161
162
163
164
    def test_parse_tokenized(self):
        cst = self.grammar(self.tokenized)
        assert not cst.error_flag

165
    def test_source_mapping_1(self):
166
167
168
169
170
171
        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
172

173
174
175
176
177
178
179
180
181
    def test_source_mapping_2(self):
        previous_index = 0
        L = len(self.code)
        for mapped_index in range(len(self.tokenized)):
            index = source_map(mapped_index, self.srcmap)
            assert previous_index <= index <= L, \
                "%i <= %i <= %i violated" % (previous_index, index, L)
            previous_index = index

182
    def test_non_token_preprocessor(self):
183
        tokenized, mapping = preprocess_comments(self.code)
184
185
186
187
188
189
190
        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):
191
        pchain = chain_preprocessors(preprocess_comments, preprocess_indentation)
192
193
194
195
196
197
198
        tokenized, mapping = pchain(self.code)
        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
199
200
    def test_error_position(self):
        orig_src = self.code.replace('#', '\x1b')
201
        prepr = chain_preprocessors(preprocess_comments, preprocess_indentation)
202
        self.grammar.max_parser_dropouts__ = 3
eckhart's avatar
eckhart committed
203
204
205
206
207
208
209
210
        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"

211
212
213
214
215
216
217

if __name__ == "__main__":
    # tp = TestTokenParsing()
    # tp.setup()
    from DHParser.testing import runner

    runner("", globals())