File: test_lexer.py

package info (click to toggle)
xonsh 0.13.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,024 kB
  • sloc: python: 46,350; makefile: 136; sh: 41; xml: 17
file content (479 lines) | stat: -rw-r--r-- 12,242 bytes parent folder | download
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
"""Tests the xonsh lexer."""
import os
import sys
from collections.abc import Sequence

sys.path.insert(0, os.path.abspath(".."))  # FIXME
from pprint import pformat

import pytest

from ply.lex import LexToken

from xonsh.lexer import Lexer

LEXER_ARGS = {"lextab": "lexer_test_table", "debug": 0}


def ensure_tuple(x):
    if isinstance(x, LexToken):
        # line numbers can no longer be solely determined from the lexer
        # x = (x.type, x.value, x.lineno, x.lexpos)
        x = (x.type, x.value, x.lexpos)
    elif isinstance(x, tuple):
        pass
    elif isinstance(x, Sequence):
        x = tuple(x)
    else:
        raise TypeError(f"{x} is not a sequence")
    return x


def tokens_equal(x, y):
    """Tests whether two token are equal."""
    xtup = ensure_tuple(x)
    ytup = ensure_tuple(y)
    return xtup == ytup


def assert_token_equal(x, y):
    """Asserts that two tokens are equal."""
    if not tokens_equal(x, y):
        msg = f"The tokens differ: {x!r} != {y!r}"
        pytest.fail(msg)
    return True


def assert_tokens_equal(x, y):
    """Asserts that two token sequences are equal."""
    if len(x) != len(y):
        msg = "The tokens sequences have different lengths: {0!r} != {1!r}\n"
        msg += "# x\n{2}\n\n# y\n{3}"
        pytest.fail(msg.format(len(x), len(y), pformat(x), pformat(y)))
    diffs = [(a, b) for a, b in zip(x, y) if not tokens_equal(a, b)]
    if len(diffs) > 0:
        msg = ["The token sequences differ: "]
        for a, b in diffs:
            msg += ["", "- " + repr(a), "+ " + repr(b)]
        msg = "\n".join(msg)
        pytest.fail(msg)
    return True


def lex_input(inp: str):
    lex = Lexer()
    lex.input(inp)
    return list(lex)


def check_token(inp, exp):
    obs = lex_input(inp)
    if len(obs) != 1:
        msg = "The observed sequence does not have length-1: {0!r} != 1\n"
        msg += "# obs\n{1}"
        pytest.fail(msg.format(len(obs), pformat(obs)))
    return assert_token_equal(exp, obs[0])


def check_tokens(inp, exp):
    obs = lex_input(inp)
    return assert_tokens_equal(exp, obs)


def check_tokens_subproc(inp, exp, stop=-1):
    obs = lex_input(f"$[{inp}]")[1:stop]
    return assert_tokens_equal(exp, obs)


def test_int_literal():
    assert check_token("42", ["NUMBER", "42", 0])
    assert check_token("4_2", ["NUMBER", "4_2", 0])


def test_hex_literal():
    assert check_token("0x42", ["NUMBER", "0x42", 0])
    assert check_token("0x4_2", ["NUMBER", "0x4_2", 0])


def test_oct_o_literal():
    assert check_token("0o42", ["NUMBER", "0o42", 0])
    assert check_token("0o4_2", ["NUMBER", "0o4_2", 0])


def test_bin_literal():
    assert check_token("0b101010", ["NUMBER", "0b101010", 0])
    assert check_token("0b10_10_10", ["NUMBER", "0b10_10_10", 0])


def test_indent():
    exp = [("INDENT", "  \t  ", 0), ("NUMBER", "42", 5), ("DEDENT", "", 0)]
    assert check_tokens("  \t  42", exp)


def test_post_whitespace():
    inp = "42  \t  "
    exp = [("NUMBER", "42", 0)]
    assert check_tokens(inp, exp)


def test_internal_whitespace():
    inp = "42  +\t65"
    exp = [("NUMBER", "42", 0), ("PLUS", "+", 4), ("NUMBER", "65", 6)]
    assert check_tokens(inp, exp)


def test_indent_internal_whitespace():
    inp = " 42  +\t65"
    exp = [
        ("INDENT", " ", 0),
        ("NUMBER", "42", 1),
        ("PLUS", "+", 5),
        ("NUMBER", "65", 7),
        ("DEDENT", "", 0),
    ]
    assert check_tokens(inp, exp)


def test_assignment():
    inp = "x = 42"
    exp = [("NAME", "x", 0), ("EQUALS", "=", 2), ("NUMBER", "42", 4)]
    assert check_tokens(inp, exp)


def test_multiline():
    inp = "x\ny"
    exp = [("NAME", "x", 0), ("NEWLINE", "\n", 1), ("NAME", "y", 0)]
    assert check_tokens(inp, exp)


def test_atdollar_expression():
    inp = "@$(which python)"
    exp = [
        ("ATDOLLAR_LPAREN", "@$(", 0),
        ("NAME", "which", 3),
        ("WS", " ", 8),
        ("NAME", "python", 9),
        ("RPAREN", ")", 15),
    ]
    assert check_tokens(inp, exp)


def test_and():
    # no preceding whitespace or other tokens, so this
    # resolves to NAME, since it doesn't make sense for
    # Python code to start with "and"
    assert check_token("and", ["NAME", "and", 0])


def test_ampersand():
    assert check_token("&", ["AMPERSAND", "&", 0])


def test_not_really_and_pre():
    inp = "![foo-and]"
    exp = [
        ("BANG_LBRACKET", "![", 0),
        ("NAME", "foo", 2),
        ("MINUS", "-", 5),
        ("NAME", "and", 6),
        ("RBRACKET", "]", 9),
    ]
    assert check_tokens(inp, exp)


def test_not_really_and_post():
    inp = "![and-bar]"
    exp = [
        ("BANG_LBRACKET", "![", 0),
        ("NAME", "and", 2),
        ("MINUS", "-", 5),
        ("NAME", "bar", 6),
        ("RBRACKET", "]", 9),
    ]
    assert check_tokens(inp, exp)


def test_not_really_and_pre_post():
    inp = "![foo-and-bar]"
    exp = [
        ("BANG_LBRACKET", "![", 0),
        ("NAME", "foo", 2),
        ("MINUS", "-", 5),
        ("NAME", "and", 6),
        ("MINUS", "-", 9),
        ("NAME", "bar", 10),
        ("RBRACKET", "]", 13),
    ]
    assert check_tokens(inp, exp)


def test_not_really_or_pre():
    inp = "![foo-or]"
    exp = [
        ("BANG_LBRACKET", "![", 0),
        ("NAME", "foo", 2),
        ("MINUS", "-", 5),
        ("NAME", "or", 6),
        ("RBRACKET", "]", 8),
    ]
    assert check_tokens(inp, exp)


def test_not_really_or_post():
    inp = "![or-bar]"
    exp = [
        ("BANG_LBRACKET", "![", 0),
        ("NAME", "or", 2),
        ("MINUS", "-", 4),
        ("NAME", "bar", 5),
        ("RBRACKET", "]", 8),
    ]
    assert check_tokens(inp, exp)


def test_not_really_or_pre_post():
    inp = "![foo-or-bar]"
    exp = [
        ("BANG_LBRACKET", "![", 0),
        ("NAME", "foo", 2),
        ("MINUS", "-", 5),
        ("NAME", "or", 6),
        ("MINUS", "-", 8),
        ("NAME", "bar", 9),
        ("RBRACKET", "]", 12),
    ]
    assert check_tokens(inp, exp)


def test_subproc_line_cont_space():
    inp = (
        "![echo --option1 value1 \\\n"
        "     --option2 value2 \\\n"
        "     --optionZ valueZ]"
    )
    exp = [
        ("BANG_LBRACKET", "![", 0),
        ("NAME", "echo", 2),
        ("WS", " ", 6),
        ("MINUS", "-", 7),
        ("MINUS", "-", 8),
        ("NAME", "option1", 9),
        ("WS", " ", 16),
        ("NAME", "value1", 17),
        ("WS", " ", 23),
        ("MINUS", "-", 5),
        ("MINUS", "-", 6),
        ("NAME", "option2", 7),
        ("WS", " ", 14),
        ("NAME", "value2", 15),
        ("WS", " ", 21),
        ("MINUS", "-", 5),
        ("MINUS", "-", 6),
        ("NAME", "optionZ", 7),
        ("WS", " ", 14),
        ("NAME", "valueZ", 15),
        ("RBRACKET", "]", 21),
    ]
    assert check_tokens(inp, exp)


def test_subproc_line_cont_nospace():
    inp = (
        "![echo --option1 value1\\\n"
        "     --option2 value2\\\n"
        "     --optionZ valueZ]"
    )
    exp = [
        ("BANG_LBRACKET", "![", 0),
        ("NAME", "echo", 2),
        ("WS", " ", 6),
        ("MINUS", "-", 7),
        ("MINUS", "-", 8),
        ("NAME", "option1", 9),
        ("WS", " ", 16),
        ("NAME", "value1", 17),
        ("WS", "\\", 23),
        ("MINUS", "-", 5),
        ("MINUS", "-", 6),
        ("NAME", "option2", 7),
        ("WS", " ", 14),
        ("NAME", "value2", 15),
        ("WS", "\\", 21),
        ("MINUS", "-", 5),
        ("MINUS", "-", 6),
        ("NAME", "optionZ", 7),
        ("WS", " ", 14),
        ("NAME", "valueZ", 15),
        ("RBRACKET", "]", 21),
    ]
    assert check_tokens(inp, exp)


def test_atdollar():
    assert check_token("@$", ["ATDOLLAR", "@$", 0])


def test_doubleamp():
    assert check_token("&&", ["AND", "and", 0])


def test_pipe():
    assert check_token("|", ["PIPE", "|", 0])


def test_doublepipe():
    assert check_token("||", ["OR", "or", 0])


def test_single_quote_literal():
    assert check_token("'yo'", ["STRING", "'yo'", 0])


def test_double_quote_literal():
    assert check_token('"yo"', ["STRING", '"yo"', 0])


def test_triple_single_quote_literal():
    assert check_token("'''yo'''", ["STRING", "'''yo'''", 0])


def test_triple_double_quote_literal():
    assert check_token('"""yo"""', ["STRING", '"""yo"""', 0])


def test_single_raw_string_literal():
    assert check_token("r'yo'", ["STRING", "r'yo'", 0])


def test_double_raw_string_literal():
    assert check_token('r"yo"', ["STRING", 'r"yo"', 0])


def test_single_f_string_literal():
    assert check_token("f'{yo}'", ["STRING", "f'{yo}'", 0])


def test_double_f_string_literal():
    assert check_token('f"{yo}"', ["STRING", 'f"{yo}"', 0])


def test_single_unicode_literal():
    assert check_token("u'yo'", ["STRING", "u'yo'", 0])


def test_double_unicode_literal():
    assert check_token('u"yo"', ["STRING", 'u"yo"', 0])


def test_single_bytes_literal():
    assert check_token("b'yo'", ["STRING", "b'yo'", 0])


def test_path_string_literal():
    assert check_token("p'/foo'", ["STRING", "p'/foo'", 0])
    assert check_token('p"/foo"', ["STRING", 'p"/foo"', 0])
    assert check_token("pr'/foo'", ["STRING", "pr'/foo'", 0])
    assert check_token('pr"/foo"', ["STRING", 'pr"/foo"', 0])
    assert check_token("rp'/foo'", ["STRING", "rp'/foo'", 0])
    assert check_token('rp"/foo"', ["STRING", 'rp"/foo"', 0])


def test_path_fstring_literal():
    assert check_token("pf'/foo'", ["STRING", "pf'/foo'", 0])
    assert check_token('pf"/foo"', ["STRING", 'pf"/foo"', 0])
    assert check_token("fp'/foo'", ["STRING", "fp'/foo'", 0])
    assert check_token('fp"/foo"', ["STRING", 'fp"/foo"', 0])
    assert check_token("pF'/foo'", ["STRING", "pF'/foo'", 0])
    assert check_token('pF"/foo"', ["STRING", 'pF"/foo"', 0])
    assert check_token("Fp'/foo'", ["STRING", "Fp'/foo'", 0])
    assert check_token('Fp"/foo"', ["STRING", 'Fp"/foo"', 0])


def test_regex_globs():
    for i in (".*", r"\d*", ".*#{1,2}"):
        for p in ("", "r", "g", "@somethingelse", "p", "pg"):
            c = f"{p}`{i}`"
            assert check_token(c, ["SEARCHPATH", c, 0])


@pytest.mark.parametrize(
    "case",
    [
        "0.0",
        ".0",
        "0.",
        "1e10",
        "1.e42",
        "0.1e42",
        "0.5e-42",
        "5E10",
        "5e+42",
        "1_0e1_0",
    ],
)
def test_float_literals(case):
    assert check_token(case, ["NUMBER", case, 0])


@pytest.mark.parametrize(
    "case", ["2>1", "err>out", "o>", "all>", "e>o", "e>", "out>", "2>&1"]
)
def test_ioredir(case):
    assert check_tokens_subproc(case, [("IOREDIRECT", case, 2)], stop=-2)


@pytest.mark.parametrize("case", [">", ">>", "<", "e>", "> ", ">>   ", "<  ", "e> "])
def test_redir_whitespace(case):
    inp = f"![{case}/path/to/file]"
    obs = lex_input(inp)
    assert obs[2].type == "WS"


@pytest.mark.parametrize(
    "s, exp",
    [
        ("", []),
        ("   \t   \n \t  ", []),
        ("echo hello", ["echo", "hello"]),
        ('echo "hello"', ["echo", '"hello"']),
        ('![echo "hello"]', ["![echo", '"hello"]']),
        ("/usr/bin/echo hello", ["/usr/bin/echo", "hello"]),
        ("$(/usr/bin/echo hello)", ["$(/usr/bin/echo", "hello)"]),
        ("C:\\Python\\python.exe -m xonsh", ["C:\\Python\\python.exe", "-m", "xonsh"]),
        ('print("""I am a triple string""")', ['print("""I am a triple string""")']),
        (
            'print("""I am a \ntriple string""")',
            ['print("""I am a \ntriple string""")'],
        ),
        ("echo $HOME", ["echo", "$HOME"]),
        ("echo -n $HOME", ["echo", "-n", "$HOME"]),
        ("echo --go=away", ["echo", "--go=away"]),
        ("echo --go=$HOME", ["echo", "--go=$HOME"]),
    ],
)
def test_lexer_split(s, exp):
    lexer = Lexer()
    obs = lexer.split(s)
    assert exp == obs


@pytest.mark.parametrize(
    "s",
    (
        "()",  # sanity
        "(",
        ")",
        "))",
        "'string\nliteral",
        "'''string\nliteral",
        "string\nliteral'",
        '"',
        "'",
        '"""',
    ),
)
def test_tolerant_lexer(s):
    lexer = Lexer(tolerant=True)
    lexer.input(s)
    error_tokens = list(tok for tok in lexer if tok.type == "ERRORTOKEN")
    assert all(tok.value in s for tok in error_tokens)  # no error messages