Debian Codegraph @

rpython/rlib/parsing/test/test_pcre_regtest.py

raw symbols SCIP
1 """This test can read and parse PCRE regression tests to try out
2 on our regular expression library.
3
4 We currently only test against testoutput7 (DFA tests). We were doing
5 testoutput1, but that was PCRE matching, which was inconsistent with
6 our matching on strings like "[ab]{1,3}(ab*|b)" against 'aabbbb'.
7 """
8
9 pcre_license = """
10 # The PCRE library is distributed under the BSD license. We have borrowed some
11 # of the regression tests (the ones that fit under the DFA scope) in order to
12 # exercise our regex implementation. Those tests are distributed under PCRE's
13 # BSD license. Here is the text:
14
15 # PCRE LICENCE
16 # ------------
17 #
18 # PCRE is a library of functions to support regular expressions whose syntax
19 # and semantics are as close as possible to those of the Perl 5 language.
20 #
21 # Release 7 of PCRE is distributed under the terms of the "BSD" licence, as
22 # specified below. The documentation for PCRE, supplied in the "doc"
23 # directory, is distributed under the same terms as the software itself.
24 #
25 # The basic library functions are written in C and are freestanding. Also
26 # included in the distribution is a set of C++ wrapper functions.
27 #
28 # THE BASIC LIBRARY FUNCTIONS
29 # ---------------------------
30 #
31 # Written by: Philip Hazel
32 # Email local part: ph10
33 # Email domain: cam.ac.uk
34 #
35 # University of Cambridge Computing Service,
36 # Cambridge, England.
37 #
38 # Copyright (c) 1997-2008 University of Cambridge
39 # All rights reserved.
40 #
41 # THE C++ WRAPPER FUNCTIONS
42 # -------------------------
43 #
44 # Contributed by: Google Inc.
45 #
46 # Copyright (c) 2007-2008, Google Inc.
47 # All rights reserved.
48 #
49 # THE "BSD" LICENCE
50 # -----------------
51 #
52 # Redistribution and use in source and binary forms, with or without
53 # modification, are permitted provided that the following conditions are met:
54 #
55 # * Redistributions of source code must retain the above copyright notice,
56 # this list of conditions and the following disclaimer.
57 #
58 # * Redistributions in binary form must reproduce the above copyright
59 # notice, this list of conditions and the following disclaimer in the
60 # documentation and/or other materials provided with the distribution.
61 #
62 # * Neither the name of the University of Cambridge nor the name of Google
63 # Inc. nor the names of their contributors may be used to endorse or
64 # promote products derived from this software without specific prior
65 # written permission.
66 #
67 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
68 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
69 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
70 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
71 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
72 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
73 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
74 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
75 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
76 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
77 # POSSIBILITY OF SUCH DAMAGE.
78 #
79 # End
80
81 """
82
83 import py
84 from rpython.rlib.parsing.regexparse import make_runner, unescape
85 import string
86 import re
87 this_dir = py.path.local(__file__).join('..')
88
89 #py.test.skip("Still in progress")
90
91 # Dumper's are objects that can dump/load the suite
92 class Dumper(object):
93 def __init__(self, file):
94 pass
95 def dump(self, tests):
96 pass
97 def load(self):
98 return []
99
100 class PickleDumper(Dumper):
101 import pickle
102 def __init__(self, fileobj):
103 self.file = fileobj
104 def dump(self, tests):
105 pickle.dump(suite, self.file)
106 def load(self):
107 suite = pickle.load(file)
108 return suite
109
110 class PythonDumper(Dumper):
111 def __init__(self, fileobj):
112 self.file = fileobj
113 def dump(self, tests):
114 self.file.write('# Auto-generated file of regular expressions from PCRE library\n')
115 self.file.write(pcre_license)
116 self.file.write('suite = []\n')
117 for test in tests:
118 self.file.write('suite.append(%r)\n' % test)
119 def load(self):
120 d = {}
121 text = self.file.read()
122 exec(text, d)
123 return d['suite']
124
125 def generate_output7():
126 """Create the testoutput7.py file from the PCRE file testoutput7"""
127 create_pcre_pickle(this_dir.join('testoutput7').open(),
128 PythonDumper(this_dir.join('pcre_test_7.py').open('w')))
129
130 def create_pcre_pickle(file, dumper):
131 """Create a filtered PCRE test file for the test."""
132 lines = [line for line in file.readlines()]
133
134 # Look for things to skip...
135 no_escape = r'(^|[^\\])(\\\\)*' # Make sure there's no escaping \
136 greedy_ops = re.compile(no_escape + r'[*?+}\(]\?') # Look for *? +? }? (?
137 back_refs = re.compile(no_escape + r'\(.*' + no_escape + r'\\1') # find a \1
138 caret_in_middle = re.compile(no_escape + r'[^\[\\]\^')
139 posix_char_classes = re.compile(no_escape + r'\[[^]]*\[:[^]]+:\][^]]*\]') # like [[:digit:]]
140 bad_backslashes = re.compile(no_escape + r'(\\Q|\\E|\\G|\\P|\\8|\\9|\\A|\\Z|\\F|\\R|\\B|\\b|\\h|\\H|\\v|\\V|\\z|\\N)') # PCRE allows \Q.....\E to quote substrings, we dont.
141
142 # Perl allows single-digit hex escapes. Change \x0 -> \x00, for example
143 expand_perl_hex = re.compile(r'\\x([0-9a-fA-F]{1})(?=[^0-9a-fA-F]|$)')
144
145 # suite = [
146 # [regex, flags, [(test,result),(test,result),...]]
147 # [regex, flags, [(test,result),(test,result),...]]
148 # ]
149 suite = []
150 while lines:
151 delim = None
152 regex = ''
153 # A line is marked by a start-delimeter and an end-delimeter.
154 # The delimeter is non-alphanumeric
155 # If a backslash follows the delimiter, then the backslash should
156 # be appended to the end. (Otherwise, \ + delim would not be a
157 # delim anymore!)
158 while 1:
159 regex += lines.pop(0)
160 if not delim:
161 if not regex.strip(): # Suppress blank lanes before delim
162 regex = ''
163 continue
164 delim = regex.strip()[0]
165 assert delim in (set(string.printable) - set(string.letters) - set(string.digits))
166 test_re = re.compile(r'%(delim)s(([^%(delim)s]|\\%(delim)s)*([^\\]))%(delim)s(\\?)([^\n\r]*)' % {'delim': delim})
167 # last two groups are an optional backslash and optional flags
168
169 matches = test_re.findall(regex)
170 if matches:
171 break
172
173 assert len(matches)==1 # check to make sure we matched right
174
175 regex = matches[0][0]
176 regex += matches[0][-2] # Add the backslash, if we gotta
177 flags = matches[0][-1] # Get the flags for the regex
178
179 # Gotta tolerate Perl's short hexes
180 regex = expand_perl_hex.sub(lambda m: r'\x0'+m.group(1), regex)
181
182 tests = []
183 if greedy_ops.search(regex) or back_refs.search(regex):
184 # Suppress complex features we can't do
185 pass
186 elif flags:
187 # Suppress any test that requires PCRE flags
188 pass
189 elif posix_char_classes.search(regex):
190 pass
191 elif caret_in_middle.search(regex):
192 pass
193 elif bad_backslashes.search(regex):
194 pass
195 else:
196 # In any other case, we're going to add the test
197 # All the above test fall through and DONT get appended
198 suite.append([regex, flags, tests])
199
200 # Now find the test and expected result
201 while lines:
202 test = lines.pop(0).strip()
203 if not test:
204 break # blank line ends the set
205 if test.endswith('\\'): # Tests that end in \ expect the \ to be chopped off
206 assert not test.endswith('\\\\\\') # Make sure not three \'s. otherwise this check will get ridiculous
207 if not test.endswith('\\\\'): # Two \'s means a real \
208 test = test[:-1]
209 test = expand_perl_hex.sub(lambda m: r'\x0'+m.group(1), test)
210
211 disqualify_test = bad_backslashes.search(test)
212
213 try:
214 test = unescape(test)
215 except Exception:
216 disqualify_test = True
217 print "Warning: could not unescape %r" % test
218
219
220 # Third line in the OUTPUT is the result, either:
221 # ' 0: ...' for a match (but this is ONLY escaped by \x__ types)
222 # 'No match' for no match
223 # (other kinds exist, but we ignore them)
224 while lines:
225 match = lines.pop(0).rstrip('\r\n')
226 match = re.sub(r'\\x([0-9a-fA-F]{2})', lambda m: chr(int(m.group(1),16)), match)
227 if match.startswith('No match') or match.startswith('Error') or match.startswith('Partial'):
228 match = None
229 break
230 elif match.startswith(' 0:'):
231 # Now we need to eat any further lines like:
232 # ' 1: ....' a subgroup match
233 match = match[4:]
234 while lines[0].strip():
235 # ' 0+ ...' is also possible here
236 if lines[0][2] in [':','+']:
237 lines.pop(0)
238 else:
239 break
240 break
241 elif not match:
242 print " *** %r ***" % match
243 raise Exception("Lost sync in output.")
244 if not disqualify_test:
245 tests.append((test,match))
246
247 # Last step, if there are regex's that dont have any tests,
248 # might as well strip them out
249 suite = [test for test in suite if test[2]]
250
251 dumper.dump(suite)
252
253 def run_individual_test(regex, tests):
254 """Run a test from the PCRE suite."""
255
256 # Process the regex and make it ready for make_runner
257 regex_to_use = regex
258
259 anchor_left = regex_to_use.startswith('^')
260 anchor_right = regex_to_use.endswith('$') and not regex_to_use.endswith('\\$')
261 if anchor_left:
262 regex_to_use = regex_to_use[1:] # chop the ^ if it's there
263 if anchor_right:
264 regex_to_use = regex_to_use[:-1] # chop the $ if it's there
265
266 if not regex_to_use:
267 #print " SKIPPED (Cant do blank regex)"
268 return
269
270 print "%s:" % regex_to_use
271
272 runner = make_runner(regex_to_use)
273
274 # Now run the test expressions against the Regex
275 for test, match in tests:
276 print "/%r/%r/" % (test, match)
277
278 # Create possible subsequences that we should test
279 if anchor_left:
280 start_range = [0]
281 else:
282 start_range = range(0, len(test))
283
284 if anchor_right:
285 subseq_gen = ( (start, len(test)) for start in start_range )
286 else:
287 # Go backwards to simulate greediness
288 subseq_gen = ( (start, end) for start in start_range for end in range(len(test)+1, start-1, -1) )
289
290 # Search the possibilities for a match...
291 for start, end in subseq_gen:
292 attempt = test[start:end]
293 if runner.recognize(attempt):
294 assert attempt==match
295 break
296 else:
297 assert match is None
298
299 def test_output7():
300 suite = PythonDumper(this_dir.join('pcre_test_7.py').open()).load()
301 while suite:
302 regex, flags, tests = suite.pop(0)
303 yield run_individual_test, regex, tests
304
305 if __name__=="__main__":
306 for fcn, regex, tests in test_output7():
307 fcn(regex,tests)