File: test_tiny_ast_nodes.py

package info (click to toggle)
pyparsing 3.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 12,200 kB
  • sloc: python: 30,867; ansic: 422; sh: 112; makefile: 24
file content (462 lines) | stat: -rw-r--r-- 13,008 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
from __future__ import annotations

import textwrap

import pyparsing as pp
import pytest

from examples.tiny.tiny_parser import parse_tiny
from examples.tiny.tiny_ast import TinyNode
from examples.tiny.tiny_engine import TinyEngine


def _run_main_and_capture(src: str, capsys: pytest.CaptureFixture[str]) -> tuple[int | None, str]:
    """Parse the Tiny program, build the main AST node, execute it, and capture stdout.

    Returns (return_value, stdout_text).
    """
    try:
        parsed = parse_tiny(src)
    except pp.ParseException as pe:
        print(pe.explain())
        raise

    main_group = parsed.program.main
    # Build a MainDeclNode via the registry
    node_cls = TinyNode.from_statement_type(main_group["type"])  # type: ignore[index]
    assert node_cls is not None, "MainDeclNode class must be registered"
    main_node = node_cls(main_group)

    engine = TinyEngine()
    ret = main_node.execute(engine)  # type: ignore[assignment]
    captured = capsys.readouterr()
    return ret, captured.out


def test_declaration_with_initializers_prints_values(capsys: pytest.CaptureFixture[str]) -> None:
    src = (
        """\
        int main(){
            int i := 42;
            string s := "Hello";
            write i; write " "; write s; write endl;
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    assert out == "42 Hello\n"
    assert ret == 0


def test_function_with_no_parameters_call_via_expr(capsys: pytest.CaptureFixture[str]) -> None:
    """Define a function that takes no parameters and returns a string.

    The main program calls it in an expression context: write greeting();
    Verifies that functions with empty parameter lists are parsed, registered,
    called via eval_expr(func_call), and their return value is used.
    """
    src = (
        """\
        string greeting(){
            return "Hello!";
        }
        int main(){
            write greeting(); write endl;
            return 0;
        }
        """
    )

    parsed = parse_tiny(src)

    # Register top-level functions with the engine
    engine = TinyEngine()
    for fdef in parsed.program.functions:
        node_cls = TinyNode.from_statement_type(fdef.type)
        fn_node = node_cls.from_parsed(fdef)
        engine.register_function(fdef.decl.name, fn_node)

    # Build and execute main
    main_group = parsed.program.main
    node_cls = TinyNode.from_statement_type(main_group["type"])  # type: ignore[index]
    assert node_cls is not None
    main_node = node_cls(main_group)
    ret = main_node.execute(engine)

    captured = capsys.readouterr()
    assert captured.out == "Hello!\n"
    assert ret == 0


def test_function_with_one_parameters_call_via_expr(capsys: pytest.CaptureFixture[str]) -> None:
    """Define a function that takes one parameters and returns a string.

    The main program calls it in an expression context: write greeting();
    Verifies that functions with empty parameter lists are parsed, registered,
    called via eval_expr(func_call), and their return value is used.
    """
    src = (
        """\
        string greeting(string name){
            return "Hello " + name + "!";
        }
        int main(){
            write greeting("Bob"); write endl;
            return 0;
        }
        """
    )

    parsed = parse_tiny(src)

    # Register top-level functions with the engine
    engine = TinyEngine()
    for fdef in parsed.program.functions:
        node_cls = TinyNode.from_statement_type(fdef.type)
        fn_node = node_cls.from_parsed(fdef)
        engine.register_function(fdef.decl.name, fn_node)

    # Build and execute main
    main_group = parsed.program.main
    node_cls = TinyNode.from_statement_type(main_group["type"])  # type: ignore[index]
    assert node_cls is not None
    main_node = node_cls(main_group)
    ret = main_node.execute(engine)

    captured = capsys.readouterr()
    assert captured.out == "Hello Bob!\n"
    assert ret == 0


def test_assignment_updates_value(capsys: pytest.CaptureFixture[str]) -> None:
    src = (
        """\
        int main(){
            int x := 1;
            x := x + 2;
            write x; write endl;
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    assert out == "3\n"
    assert ret == 0


def test_repeat_until_prints_n_times(capsys: pytest.CaptureFixture[str]) -> None:
    src = (
        """\
        int main(){
            int i := 5;
            repeat
                write "Hello World!"; write endl;
                i := i - 1;
            until i = 0
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    lines = [ln for ln in out.splitlines() if ln.strip() != ""]
    assert len(lines) == 5
    assert all(ln == "Hello World!" for ln in lines)
    assert ret == 0


def test_read_statement_prompts_and_assigns(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch) -> None:
    # Program declares x as int, reads it from input, and writes it back
    src = (
        """\
        int main(){
            int x;
            read x;
            write x; write endl;
            return 0;
        }
        """
    )

    # Simulate user entering 17 at the prompt
    monkeypatch.setattr("builtins.input", lambda prompt="": "17")

    parsed = parse_tiny(src)
    main_group = parsed.program.main
    node_cls = TinyNode.from_statement_type(main_group["type"])  # type: ignore[index]
    assert node_cls is not None
    main_node = node_cls(main_group)

    engine = TinyEngine()
    ret = main_node.execute(engine)

    captured = capsys.readouterr()
    # input() prints the prompt, then write prints the value and newline
    assert captured.out == "17\n"
    assert ret == 0


def test_if_then_true_branch(capsys: pytest.CaptureFixture[str]) -> None:
    src = (
        """\
        int main(){
            int x := 5;
            if x > 0 then
                write "T"; write endl;
            end
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    assert out == "T\n"
    assert ret == 0


def test_if_then_else_false_goes_else(capsys: pytest.CaptureFixture[str]) -> None:
    src = (
        """\
        int main(){
            int x := 0;
            if x > 0 then
                write "T";
            else
                write "F";
            end
            write endl;
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    assert out == "F\n"
    assert ret == 0


def test_if_then_elseif_chain_matches_middle(capsys: pytest.CaptureFixture[str]) -> None:
    src = (
        """\
        int main(){
            int x := 2;
            if x = 1 then
                write "one";
            elseif x = 2 then
                write "two";
            elseif x = 3 then
                write "three";
            else
                write "other";
            end
            write endl;
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    assert out == "two\n"
    assert ret == 0


def test_if_then_elseif_else_falls_to_else(capsys: pytest.CaptureFixture[str]) -> None:
    src = (
        """\
        int main(){
            int x := 99;
            if x = 1 then
                write "one";
            elseif x = 2 then
                write "two";
            elseif x = 3 then
                write "three";
            else
                write "else";
            end
            write endl;
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    assert out == "else\n"
    assert ret == 0


def test_return_inside_repeat_exits_function(capsys: pytest.CaptureFixture[str]) -> None:
    # Return from within a repeat loop body should exit the function immediately
    src = (
        """\
        int main(){
            int i := 1;
            repeat
                write "before"; write endl;
                return 7;
                write "after"; write endl;
            until i = 0
            write "unreached"; write endl;
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    # Expect only the text before the return and the function to return 7
    assert out == "before\n"
    assert ret == 7


def test_return_inside_if_then_branch(capsys: pytest.CaptureFixture[str]) -> None:
    # Return inside the 'then' branch should exit the function
    src = (
        """\
        int main(){
            int x := 1;
            if x = 1 then
                write "T"; write endl;
                return 1;
                write "after-then"; write endl;
            end
            write "unreached"; write endl;
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    assert out == "T\n"
    assert ret == 1


def test_return_inside_if_elseif_branch(capsys: pytest.CaptureFixture[str]) -> None:
    # Return inside an elseif branch should exit the function
    src = (
        """\
        int main(){
            int x := 2;
            if x = 1 then
                write "one"; write endl;
            elseif x = 2 then
                write "two"; write endl;
                return 2;
                write "after-elseif"; write endl;
            else
                write "else"; write endl;
            end
            write "unreached"; write endl;
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    assert out == "two\n"
    assert ret == 2


def test_return_inside_if_else_branch(capsys: pytest.CaptureFixture[str]) -> None:
    # Return inside the else branch should exit the function
    src = (
        """\
        int main(){
            int x := 99;
            if x = 1 then
                write "one"; write endl;
            elseif x = 2 then
                write "two"; write endl;
            else
                write "else"; write endl;
                return 3;
                write "after-else"; write endl;
            end
            write "unreached"; write endl;
            return 0;
        }
        """
    )
    ret, out = _run_main_and_capture(src, capsys)
    assert out == "else\n"
    assert ret == 3


def test_all_operations_arith_string_boolean(capsys: pytest.CaptureFixture[str]) -> None:
    """Exercise arithmetic, string, relational, and boolean operators.

    Verifies:
    - Arithmetic: +, -, *, /, unary +/-
    - String concatenation with '+'
    - Relational: <, >, =, <>, >=, <= (numeric and string comparisons)
    - Boolean: &&, || with correct precedence relative to relational
    """
    src = (
        """\
        int main(){
            /* arithmetic */
            write 1 + 2; write endl;         /* 3 */
            write 5 - 3; write endl;         /* 2 */
            write 2 * 4; write endl;         /* 8 */
            write 5 / 2; write endl;         /* 2.5 */
            write -5; write endl;            /* -5 */
            write +5; write endl;            /* 5 */

            /* string concatenation */
            write "Hello " + "World"; write endl;  /* Hello World */

            /* relational numeric */
            write 1 < 2; write endl;         /* True */
            write 3 > 4; write endl;         /* False */
            write 5 = 5; write endl;         /* True */
            write 5 <> 6; write endl;        /* True */
            write 3 >= 3; write endl;        /* True */
            write 2 <= 1; write endl;        /* False */

            /* relational string (lexicographic) */
            write "a" < "b"; write endl;     /* True */
            write "b" > "a"; write endl;     /* True */
            write "x" = "x"; write endl;     /* True */
            write "a" <> "b"; write endl;    /* True */
            write "a" <= "a"; write endl;    /* True */
            write "aa" >= "ab"; write endl;  /* False */

            /* boolean ops (with relational sub-exprs) */
            write 1 && 0; write endl;        /* False */
            write 1 || 0; write endl;        /* True */
            write 0 || 0; write endl;        /* False */
            write 1 < 2 && 2 < 3; write endl;  /* True */
            write 1 < 2 && 2 > 3 || 1; write endl;  /* True (and before or) */

            return 0;
        }
        """
    )

    ret, out = _run_main_and_capture(src, capsys)

    expected = (
        textwrap.dedent(
        """\
        3
        2
        8
        2.5
        -5
        5
        Hello World
        True
        False
        True
        True
        True
        False
        True
        True
        True
        True
        True
        False
        False
        True
        False
        True
        True
        """
        )
    )
    # Normalize potential trailing spaces/newlines
    assert out == expected
    assert ret == 0