1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
|
import unittest
import pytest
from tatsu import tool
from tatsu.exceptions import FailedParse, FailedToken
from tatsu.ngcodegen import codegen
from tatsu.parser import EBNFBuffer
from tatsu.tool import compile
from tatsu.util import trim
class SyntaxTests(unittest.TestCase):
def test_update_ast(self):
grammar = """
foo = name:"1" [ name: bar ] ;
bar = { "2" } * ;
"""
m = compile(grammar, 'Keywords')
ast = m.parse('1 2')
self.assertEqual(['1', ['2']], ast.name)
grammar = """
start = items: { item } * $ ;
item = @:{ subitem } * "0" ;
subitem = ?/1+/? ;
"""
m = compile(grammar, 'Update')
ast = m.parse('1101110100', nameguard=False)
self.assertEqual([['11'], ['111'], ['1'], []], ast.items_)
def test_include_and_override(self):
gr = 'included_grammar'
included_grammar = "plu = 'aaaa';"
overridden = "%s@override\nplu = 'plu';"
inclusion = f'#include :: {gr}.ebnf\n'
including_grammar = overridden % (inclusion)
whole_grammar = overridden % (included_grammar)
class FakeIncludesBuffer(EBNFBuffer):
def get_include(self, source, filename):
return included_grammar, source + '/' + filename
compile(FakeIncludesBuffer(whole_grammar), 'test')
compile(FakeIncludesBuffer(including_grammar), 'test')
def test_ast_assignment(self):
grammar = """
n = @: {"a"}* $ ;
f = @+: {"a"}* $ ;
nn = @: {"a"}* @: {"b"}* $ ;
nf = @: {"a"}* @+: {"b"}* $ ;
fn = @+: {"a"}* @: {"b"}* $ ;
ff = @+: {"a"}* @+: {"b"}* $ ;
"""
model = compile(grammar, 'test')
def p(input, rule):
return model.parse(input, start=rule, whitespace='')
e = self.assertEqual
e([], p('', 'n'))
e(['a'], p('a', 'n'))
e(['a', 'a'], p('aa', 'n'))
e([[]], p('', 'f'))
e([['a']], p('a', 'f'))
e([['a', 'a']], p('aa', 'f'))
for r in ('nn', 'nf', 'fn', 'ff'):
e([[], []], p('', r))
e([['a'], []], p('a', r))
e([[], ['b']], p('b', r))
e([['a', 'a'], []], p('aa', r))
e([[], ['b', 'b']], p('bb', r))
e([['a', 'a'], ['b']], p('aab', r))
def test_optional_closure(self):
grammar = 'start = foo+:"x" foo:{"y"}* {foo:"z"}* ;'
model = compile(grammar, 'test')
ast = model.parse('xyyzz', nameguard=False)
self.assertEqual(['x', ['y', 'y'], 'z', 'z'], ast.foo)
grammar = 'start = foo+:"x" [foo+:{"y"}*] {foo:"z"}* ;'
model = compile(grammar, 'test')
ast = model.parse('xyyzz', nameguard=False)
self.assertEqual(['x', ['y', 'y'], 'z', 'z'], ast.foo)
grammar = 'start = foo+:"x" foo:[{"y"}*] {foo:"z"}* ;'
model = compile(grammar, 'test')
ast = model.parse('xyyzz', nameguard=False)
self.assertEqual(['x', ['y', 'y'], 'z', 'z'], ast.foo)
grammar = 'start = foo+:"x" [foo:{"y"}*] {foo:"z"}* ;'
model = compile(grammar, 'test')
ast = model.parse('xyyzz', nameguard=False)
self.assertEqual(['x', ['y', 'y'], 'z', 'z'], ast.foo)
def test_optional_sequence(self):
grammar = """
start = '1' ['2' '3'] '4' $ ;
"""
model = compile(grammar, 'test')
ast = model.parse('1234', nameguard=False)
self.assertEqual(('1', '2', '3', '4'), ast)
grammar = """
start = '1' foo:['2' '3'] '4' $ ;
"""
model = compile(grammar, 'test')
ast = model.parse('1234', nameguard=False)
self.assertEqual(['2', '3'], ast.foo)
def test_group_ast(self):
grammar = """
start = '1' ('2' '3') '4' $ ;
"""
model = compile(grammar, 'test')
ast = model.parse('1234', nameguard=False)
self.assertEqual(('1', '2', '3', '4'), ast)
def test_partial_options(self):
grammar = """
start
=
[a]
[
'A' 'A'
|
'A' 'B'
]
$
;
a
=
'A' !('A'|'B')
;
"""
model = compile(grammar, 'test')
ast = model.parse('AB', nameguard=False)
self.assertEqual(('A', 'B'), ast)
def test_partial_choice(self):
grammar = """
start
=
o:[o]
x:'A'
$
;
o
=
'A' a:'A'
|
'A' b:'B'
;
"""
model = compile(grammar, 'test')
ast = model.parse('A', nameguard=False)
self.assertEqual({'x': 'A', 'o': None}, ast)
def test_new_override(self):
grammar = """
start
=
@:'a' {@:'b'}
$
;
"""
model = compile(grammar, 'test')
ast = model.parse('abb', nameguard=False)
self.assertEqual(['a', 'b', 'b'], ast)
def test_list_override(self):
grammar = """
start
=
@+:'a' {@:'b'}
$
;
"""
model = compile(grammar, 'test')
ast = model.parse('a', nameguard=False)
self.assertEqual(['a'], ast)
grammar = """
start
=
@:'a' {@:'b'}
$
;
"""
model = compile(grammar, 'test')
ast = model.parse('a', nameguard=False)
self.assertEqual('a', ast)
def test_based_rule(self):
grammar = """\
start
=
b $
;
a
=
@:'a'
;
b < a
=
{@:'b'}
;
"""
model = compile(grammar, 'test')
ast = model.parse('abb', nameguard=False)
self.assertEqual(('a', 'b', 'b'), ast)
self.assertEqual(trim(grammar), str(model))
def test_rule_include(self):
grammar = """
start = b $;
a = @:'a' ;
b = >a {@:'b'} ;
"""
model = compile(grammar, 'test')
ast = model.parse('abb', nameguard=False)
self.assertEqual(('a', 'b', 'b'), ast)
def test_48_rule_override(self):
grammar = """
start = ab $;
ab = 'xyz' ;
@override
ab = @:'a' {@:'b'} ;
"""
model = compile(grammar, 'test')
ast = model.parse('abb', nameguard=False)
self.assertEqual(('a', 'b', 'b'), ast)
def test_failed_ref(self):
grammar = r"""
final = object;
type = /[^\s=()]+/;
object = '('type')' '{' @:{pair} {',' @:{pair}}* [','] '}';
pair = key '=' value;
list = '('type')' '[' @:{object} {',' @:{object}}* [','] ']';
key = /[^\s=]+/;
value = @:(string|list|object|unset|boolean|number|null) [','];
null = '('type')' @:{ 'null' };
boolean = /(true|false)/;
unset = '<unset>';
string = '"' @:/[^"]*/ '"';
number = /-?[0-9]+/;
"""
model = compile(grammar, 'final')
codegen(model)
model.parse('(sometype){boolean = true}')
def test_empty_match_token(self):
grammar = """
table = { row }+ ;
row = (cell1:cell "|" cell2:cell) "\n";
cell = /[a-z]+/ ;
"""
try:
compile(grammar, 'model')
self.fail('allowed empty token')
except FailedParse:
pass
def test_empty_closure(self):
grammar = """
start = {'x'}+ {} 'y'$;
"""
model = compile(grammar, 'test')
codegen(model)
ast = model.parse('xxxy', nameguard=False)
self.assertEqual((['x', 'x', 'x'], [], 'y'), ast)
def test_parseinfo(self):
grammar = """
start = head:{'x'}+ {} tail:'y'$;
"""
model = compile(grammar, 'test')
ast = model.parse('xxxy', nameguard=False, parseinfo=True)
self.assertIsNotNone(ast)
self.assertIsNotNone(ast.head)
self.assertIsNotNone(ast.tail)
self.assertIsNotNone(ast.parseinfo)
def test_raw_string(self):
grammar = r"""
start = r'am\nraw' ;
"""
pretty = r"""
start
=
'am\\nraw'
;
"""
model = compile(grammar, 'start')
print(model.pretty())
self.assertEqual(trim(pretty), model.pretty())
def test_any(self):
grammar = """
start = /./ 'xx' /./ /./ 'yy' $;
"""
model = compile(grammar, 'start')
ast = model.parse('1xx 2 yy')
self.assertEqual(('1', 'xx', ' ', '2', 'yy'), ast)
def test_constant(self):
grammar = """
start = ()
_0:`0` _1:`+1` _n123:`-123`
_xF:`0xF`
_string:`string`
_string_space:`'string space'`
_true:`True` _false:`False`
$;
"""
model = compile(grammar)
ast = model.parse('')
self.assertEqual(ast._0, 0)
self.assertEqual(ast._1, 1)
self.assertEqual(ast._n123, -123)
self.assertEqual(ast._xF, 0xF)
self.assertEqual(ast._string, 'string')
self.assertEqual(ast._string_space, 'string space')
self.assertEqual(ast._true, True)
self.assertEqual(ast._false, False)
def test_parse_hash():
grammar = r"""
@@comments :: /@@@@@@@/
@@eol_comments :: /@@@@@@@/
start = '#' ;
"""
parser = compile(grammar, eol_comments='')
parser.parse('#', trace=True)
def test_parse_void():
grammar = r"""
start = () $ ;
"""
ast = tool.parse(grammar, '')
print(ast)
assert ast is None
def test_no_default_comments():
grammar = """
start = 'a' $;
"""
text = """
# no comments are valid
a
"""
with pytest.raises(FailedToken):
tool.parse(grammar, text)
import re
@pytest.mark.parametrize(
"comment,option",
[
pytest.param(
"# This comment should be stripped",
{
"eol_comments_re": re.compile(r"(?m)#.*?$"),
"eol_comments": r"(?m)#.*?$",
},
id="eol_comments override",
),
pytest.param(
"(* This comment should be stripped *)",
{
"comments_re": re.compile(r"(?sm)[(][*](?:.|\n)*?[*][)]"),
"comments": r"(?sm)[(][*](?:.|\n)*?[*][)]",
},
id="comments override",
),
],
)
def test_deprecated_comments_override_failures(comment, option):
"""
# TODO: remove this test after {eol_}comments_re are no longer supported
"""
grammar = """
@@comments :: /@@@@@@/
@@eol_comments :: /@@@@@@/
start = 'a' $;
"""
text = f"""
{comment}
a
"""
with pytest.raises(AttributeError, match=""):
tool.parse(grammar, text, **option)
|