-
-
Notifications
You must be signed in to change notification settings - Fork 147
/
word_parse_test.py
executable file
·532 lines (406 loc) · 14.9 KB
/
word_parse_test.py
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#!/usr/bin/env python
# Copyright 2016 Andy Chu. All rights reserved.
# 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
"""
word_parse_test.py: Tests for word_parse.py
"""
import unittest
from asdl import const
from core import alloc
from core import test_lib
from core import word
from core import util
from osh.meta import ast, Id, types
from osh import ast_lib
from osh import parse_lib
from osh.word_parse import WordParser # module under test
arith_expr_e = ast.arith_expr_e
lex_mode_e = types.lex_mode_e
def _InitWordParserWithArena(s):
pool = alloc.Pool()
arena = pool.NewArena()
arena.PushSource('word_parse_test.py')
line_reader, lexer = parse_lib.InitLexer(s, arena)
w_parser = WordParser(lexer, line_reader)
return arena, w_parser
def InitWordParser(s):
_, w_parser = _InitWordParserWithArena(s)
return w_parser
def _assertReadWordWithArena(test, word_str):
print('\n---', word_str)
arena, w_parser = _InitWordParserWithArena(word_str)
w = w_parser.ReadWord(lex_mode_e.OUTER)
if w:
ast_lib.PrettyPrint(w)
else:
err = w_parser.Error()
test.fail("Couldn't parse %r: %s" % (word_str, err))
# Next word must be Eof_Real
w2 = w_parser.ReadWord(lex_mode_e.OUTER)
test.assertTrue(
test_lib.TokenWordsEqual(ast.TokenWord(ast.token(Id.Eof_Real, '')), w2),
w2)
return arena, w
def _assertReadWord(test, word_str):
_, w = _assertReadWordWithArena(test, word_str)
return w
def _assertSpanForWord(test, code_str):
arena, w = _assertReadWordWithArena(test, code_str)
span_id = word.LeftMostSpanForWord(w)
print(code_str)
print(span_id)
if span_id != const.NO_INTEGER:
span = arena.GetLineSpan(span_id)
print(span)
def _assertReadWordFailure(test, word_str):
print('\n---', word_str)
w_parser = InitWordParser(word_str)
try:
w = w_parser.ReadWord(lex_mode_e.OUTER)
except util.ParseError as e:
print(e)
return
if not w:
print(w_parser.Error())
return
ast_lib.PrettyPrint(w)
test.fail('Expected a parser error, got %r' % w)
def _GetSuffixOp(test, w):
"""Get a single transform op"""
test.assertEqual(1, len(w.parts))
return w.parts[0].suffix_op
def _GetPrefixOp(test, w):
"""Get a single transform op"""
test.assertEqual(1, len(w.parts))
return w.parts[0].prefix_op
def _GetVarSub(test, w):
"""Get a single transform op"""
test.assertEqual(1, len(w.parts))
return w.parts[0]
class WordParserTest(unittest.TestCase):
def testStaticEvalWord(self):
expr = r'\EOF' # Quoted here doc delimiter
w_parser = InitWordParser(expr)
w = w_parser.ReadWord(lex_mode_e.OUTER)
ok, s, quoted = word.StaticEval(w)
self.assertEqual(True, ok)
self.assertEqual('EOF', s)
self.assertEqual(True, quoted)
def testDisambiguatePrefix(self):
w = _assertReadWord(self, '${#}')
self.assertEqual('#', _GetVarSub(self, w).token.val)
w = _assertReadWord(self, '${!}')
self.assertEqual('!', _GetVarSub(self, w).token.val)
w = _assertReadWord(self, '${?}')
self.assertEqual('?', _GetVarSub(self, w).token.val)
w = _assertReadWord(self, '${var}')
w = _assertReadWord(self, '${15}')
w = _assertReadWord(self, '${#var}')
self.assertEqual(Id.VSub_Pound, _GetPrefixOp(self, w))
w = _assertReadWord(self, '${!ref}')
self.assertEqual(Id.VSub_Bang, _GetPrefixOp(self, w))
# Length of length
w = _assertReadWord(self, '${##}')
self.assertEqual('#', _GetVarSub(self, w).token.val)
self.assertEqual(Id.VSub_Pound, _GetPrefixOp(self, w))
w = _assertReadWord(self, '${array[0]}')
self.assertEqual(1, len(w.parts))
w = _assertReadWord(self, '${array[@]}')
self.assertEqual(1, len(w.parts))
# Length of element
w = _assertReadWord(self, '${#array[0]}')
self.assertEqual(1, len(w.parts))
self.assertEqual(Id.VSub_Pound, _GetPrefixOp(self, w))
# Ref for element
w = _assertReadWord(self, '${!array[0]}')
self.assertEqual(1, len(w.parts))
self.assertEqual(Id.VSub_Bang, _GetPrefixOp(self, w))
w = _assertReadWord(self, '${var#prefix}')
self.assertEqual(1, len(w.parts))
self.assertEqual(Id.VOp1_Pound, _GetSuffixOp(self, w).op_id)
w = _assertReadWord(self, '${!var#prefix}')
self.assertEqual(1, len(w.parts))
self.assertEqual(Id.VSub_Bang, _GetPrefixOp(self, w))
self.assertEqual(Id.VOp1_Pound, _GetSuffixOp(self, w).op_id)
_assertReadWordFailure(self, '${#var#prefix}')
# Allowed by bash, but we don't parse it. Use len=$#; echo ${len#2}
# instead.
_assertReadWordFailure(self, '${##2}')
def testVarOf(self):
w = _assertReadWord(self, '${name}')
w = _assertReadWord(self, '${name[0]}')
w = _assertReadWord(self, '${array[@]}')
# Should be DISALLOWED!
#w = _assertReadWord(self, '${11[@]}')
def assertUnquoted(self, expected, w):
ok, s, quoted = word.StaticEval(w)
self.assertTrue(ok)
self.assertEqual(expected, s)
self.assertFalse(quoted)
def testPatSub(self):
w = _assertReadWord(self, '${var/pat/replace}')
op = _GetSuffixOp(self, w)
self.assertFalse(op.do_all)
self.assertFalse(op.do_prefix)
self.assertFalse(op.do_suffix)
self.assertUnquoted('pat', op.pat)
self.assertUnquoted('replace', op.replace)
w = _assertReadWord(self, '${var//pat/replace}') # sub all
op = _GetSuffixOp(self, w)
self.assertTrue(op.do_all)
self.assertUnquoted('pat', op.pat)
self.assertUnquoted('replace', op.replace)
w = _assertReadWord(self, '${var/%pat/replace}') # prefix
op = _GetSuffixOp(self, w)
self.assertTrue(op.do_suffix)
self.assertUnquoted('pat', op.pat)
self.assertUnquoted('replace', op.replace)
w = _assertReadWord(self, '${var/#pat/replace}') # suffix
op = _GetSuffixOp(self, w)
self.assertTrue(op.do_prefix)
self.assertUnquoted('pat', op.pat)
self.assertUnquoted('replace', op.replace)
w = _assertReadWord(self, '${var/pat}') # no replacement
w = _assertReadWord(self, '${var//pat}') # no replacement
op = _GetSuffixOp(self, w)
self.assertTrue(op.do_all)
self.assertUnquoted('pat', op.pat)
self.assertEqual(None, op.replace)
# replace with slash
w = _assertReadWord(self, '${var/pat//}')
op = _GetSuffixOp(self, w)
self.assertUnquoted('pat', op.pat)
self.assertUnquoted('/', op.replace)
# replace with two slashes unquoted
w = _assertReadWord(self, '${var/pat///}')
op = _GetSuffixOp(self, w)
self.assertUnquoted('pat', op.pat)
self.assertUnquoted('//', op.replace)
# replace with two slashes quoted
w = _assertReadWord(self, '${var/pat/"//"}')
op = _GetSuffixOp(self, w)
self.assertUnquoted('pat', op.pat)
ok, s, quoted = word.StaticEval(op.replace)
self.assertTrue(ok)
self.assertEqual('//', s)
self.assertTrue(quoted)
# Real example found in the wild!
# http://www.oilshell.org/blog/2016/11/07.html
w = _assertReadWord(self, r'${var////\\/}')
op = _GetSuffixOp(self, w)
self.assertTrue(op.do_all)
self.assertUnquoted('/', op.pat)
ok, s, quoted = word.StaticEval(op.replace)
self.assertTrue(ok)
self.assertEqual(r'\/', s)
def testSlice(self):
w = _assertReadWord(self, '${foo:0}')
# No length
self.assertEqual(None, _GetSuffixOp(self, w).length)
w = _assertReadWord(self, '${foo:0:1}')
w = _assertReadWord(self, '${foo:1+2:2+3}')
# This is allowed
w = _assertReadWord(self, '${foo::1}')
# No beginning
self.assertEqual(None, _GetSuffixOp(self, w).begin)
def testLength(self):
# Synonym for $#, had a bug here
w = _assertReadWord(self, '${#@}')
self.assertTrue(Id.VSub_Pound, _GetPrefixOp(self, w))
# Length of arg 11
w = _assertReadWord(self, '${#11}')
self.assertTrue(Id.VSub_Pound, _GetPrefixOp(self, w))
w = _assertReadWord(self, '${#str}')
self.assertTrue(Id.VSub_Pound, _GetPrefixOp(self, w))
w = _assertReadWord(self, '${#array[0]}')
# BUG!
#self.assertTrue(VS_POUND, _GetSuffixOp(self, w).id)
w = _assertReadWord(self, '${#array["key"]}')
# BUG!
#self.assertTrue(Id.VSub_POUND, _GetSuffixOp(self, w).id)
def testUnary(self):
w = _assertReadWord(self, '${var#}')
self.assertTrue(Id.VOp1_Pound, _GetSuffixOp(self, w).op_id)
w = _assertReadWord(self, '${var#prefix}')
self.assertTrue(Id.VOp1_Pound, _GetSuffixOp(self, w).op_id)
w = _assertReadWord(self, '${var##}')
self.assertTrue(Id.VOp1_DPound, _GetSuffixOp(self, w).op_id)
w = _assertReadWord(self, '${var##prefix}')
self.assertTrue(Id.VOp1_DPound, _GetSuffixOp(self, w).op_id)
w = _assertReadWord(self, '${var%suffix}')
w = _assertReadWord(self, '${var%%suffix}')
def testArrayOp(self):
w = _assertReadWord(self, '${array[0]}')
w = _assertReadWord(self, '${array[5+5]}')
w = _assertReadWord(self, '${array[@]}')
w = _assertReadWord(self, '${array[*]}')
def testTestOp(self):
w = _assertReadWord(self, '${var:-default]}')
def testTildeLike(self):
w = _assertReadWord(self, '~/git/oilshell/oil')
w = _assertReadWord(self, '~andy/git/oilshell/oil')
w = _assertReadWord(self, '~andy_c/git/oilshell/oil')
w = _assertReadWord(self, '~andy.c/git/oilshell/oil')
w = _assertReadWord(self, '~andy-c/git/oilshell/oil')
w = _assertReadWord(self, '~andy-c:git/oilshell/oil')
def testRead(self):
CASES = [
'ls "foo"',
'$(( 1 + 2 ))',
'$(echo $(( 1 )) )', # OLD BUG: arith sub within command sub
'echo ${#array[@]} b', # Had a bug here
'echo $(( ${#array[@]} ))', # Bug here
# Had a bug: unary minus
#'${mounted_disk_regex:0:-1}',
'echo ${@%suffix}', # had a bug here
'${@}',
'echo ${var,,}',
'echo ${var,,?}',
# Line continuation tests
'${\\\nfoo}', # VS_1
'${foo\\\n}', # VS_2
'${foo#\\\nyo}', # VS_ARG_UNQ
'"${foo#\\\nyo}"', # VS_ARG_DQ
]
for expr in CASES:
print('---')
print(expr)
print()
w_parser = InitWordParser(expr)
while True:
w = w_parser.ReadWord(lex_mode_e.OUTER)
if w is None:
e = w_parser.Error()
print('Error in word parser: %s' % e)
self.fail(e)
ast_lib.PrettyPrint(w)
if word.CommandId(w) == Id.Eof_Real:
break
def testReadComment(self):
# Test that we get Id.Op_Newline
code = 'foo # comment\nbar #comment\n'
w_parser = InitWordParser(code)
w = w_parser.ReadWord(lex_mode_e.OUTER)
assert w
self.assertEqual('foo', w.parts[0].token.val)
w = w_parser.ReadWord(lex_mode_e.OUTER)
assert w
self.assertEqual(Id.Op_Newline, w.token.id)
w = w_parser.ReadWord(lex_mode_e.OUTER)
assert w
self.assertEqual('bar', w.parts[0].token.val)
w = w_parser.ReadWord(lex_mode_e.OUTER)
assert w
self.assertEqual(Id.Op_Newline, w.token.id)
w = w_parser.ReadWord(lex_mode_e.OUTER)
assert w
self.assertEqual(Id.Eof_Real, w.token.id)
def testReadRegex(self):
# Test that we get Id.Op_Newline
code = '(foo|bar)'
w_parser = InitWordParser(code)
w_parser.next_lex_mode = lex_mode_e.BASH_REGEX # needed at beginning
w = w_parser.ReadWord(lex_mode_e.BASH_REGEX)
assert w
self.assertEqual('(', w.parts[0].token.val)
self.assertEqual('foo', w.parts[1].token.val)
self.assertEqual('|', w.parts[2].token.val)
self.assertEqual('bar', w.parts[3].token.val)
self.assertEqual(')', w.parts[4].token.val)
self.assertEqual(5, len(w.parts))
w = w_parser.ReadWord(lex_mode_e.OUTER)
assert w
self.assertEqual(Id.Eof_Real, w.token.id)
def testReadArithWord(self):
w = _assertReadWord(self, '$(( f(x) ))')
child = w.parts[0].anode
self.assertEqual(arith_expr_e.FuncCall, child.tag)
w = _assertReadWord(self, '$(( f(1, 2, 3, 4) ))')
child = w.parts[0].anode
self.assertEqual(arith_expr_e.FuncCall, child.tag)
self.assertEqual(4, len(child.args))
def testReadArith(self):
CASES = [
'1 + 2',
'a + b',
'$a * $b',
'${a} * ${b}',
'$(echo 1) * $(echo 2)',
'`echo 1` + 2',
'$((1 + 2)) * $((3 + 4))',
"'single quoted'", # Allowed by oil but not bash
'"${a}" + "${b}"', # Ditto
'$# + $$',
# This doesn't work but does in bash -- should be 15
#'$(( $(echo 1)$(echo 2) + 3 ))',
'$(( x[0] < 5 ))',
'$(( ++i ))',
'$(( i++ ))',
'$(( x -= 1))',
'$(( x |= 1))',
'$(( x[0] = 1 ))',
'$(( 1 | 0 ))',
'$((0x$size))',
]
for expr in CASES:
print('---')
print(expr)
print()
w_parser = InitWordParser(expr)
w_parser._Next(lex_mode_e.ARITH) # Can we remove this requirement?
while True:
w = w_parser.ReadWord(lex_mode_e.ARITH)
if not w:
err = w_parser.Error()
print('ERROR', err)
self.fail(err)
break
ast_lib.PrettyPrint(w)
if word.CommandId(w) in (Id.Eof_Real, Id.Unknown_Tok):
break
def testMultiLine(self):
w_parser = InitWordParser("""\
ls foo
# Multiple newlines and comments should be ignored
ls bar
""")
print('--MULTI')
w = w_parser.ReadWord(lex_mode_e.OUTER)
parts = [ast.LiteralPart(ast.token(Id.Lit_Chars, 'ls'))]
test_lib.AssertAsdlEqual(self, ast.CompoundWord(parts), w)
w = w_parser.ReadWord(lex_mode_e.OUTER)
parts = [ast.LiteralPart(ast.token(Id.Lit_Chars, 'foo'))]
test_lib.AssertAsdlEqual(self, ast.CompoundWord(parts), w)
w = w_parser.ReadWord(lex_mode_e.OUTER)
t = ast.token(Id.Op_Newline, '\n')
test_lib.AssertAsdlEqual(self, ast.TokenWord(t), w)
w = w_parser.ReadWord(lex_mode_e.OUTER)
parts = [ast.LiteralPart(ast.token(Id.Lit_Chars, 'ls'))]
test_lib.AssertAsdlEqual(self, ast.CompoundWord(parts), w)
w = w_parser.ReadWord(lex_mode_e.OUTER)
parts = [ast.LiteralPart(ast.token(Id.Lit_Chars, 'bar'))]
test_lib.AssertAsdlEqual(self, ast.CompoundWord(parts), w)
w = w_parser.ReadWord(lex_mode_e.OUTER)
t = ast.token(Id.Op_Newline, '\n')
test_lib.AssertAsdlEqual(self, ast.TokenWord(t), w)
w = w_parser.ReadWord(lex_mode_e.OUTER)
t = ast.token(Id.Eof_Real, '')
test_lib.AssertAsdlEqual(self, ast.TokenWord(t), w)
def testParseErrorLocation(self):
w = _assertSpanForWord(self, 'a=(1 2 3)')
w = _assertSpanForWord(self, 'foo')
w = _assertSpanForWord(self, '\\$')
w = _assertSpanForWord(self, "''")
w = _assertSpanForWord(self, "'sq'")
w = _assertSpanForWord(self, '""')
w = _assertSpanForWord(self, '"dq"')
w = _assertSpanForWord(self, '$(echo command sub)')
w = _assertSpanForWord(self, '$(( 1 + 2 ))')
w = _assertSpanForWord(self, '~user')
w = _assertSpanForWord(self, '${var#}')
if __name__ == '__main__':
unittest.main()