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 Tests for the lepl.support.list module.
32 '''
33
34
35 from unittest import TestCase
36
37 from lepl import *
38 from lepl._test.base import assert_str
39 from lepl.support.list import clone_sexpr, count_sexpr, join, \
40 sexpr_flatten, sexpr_to_str
41
42
44
49 test([])
50 test([1,2,3])
51 test([[1],2,3])
52 test([[[1]],2,3])
53 test([[[1]],2,[3]])
54 test([[[1]],'2',[3]])
55 test(((1),List([2,3,[4]])))
56
58 def test(list_, value):
59 measured = count_sexpr(list_)
60 assert measured == value, measured
61 test([], 0)
62 test([1,2,3], 3)
63 test([[1],2,3], 3)
64 test([[[1,2],3],'four',5], 5)
65
67 def test(list_, joined, flattened):
68 if joined is not None:
69 result = join(list_)
70 assert result == joined, result
71 result = sexpr_flatten(list_)
72 assert result == flattened, result
73 test([[1],[2, [3]]], [1,2,[3]], [1,2,3])
74 test([], [], [])
75 test([1,2,3], None, [1,2,3])
76 test([[1],2,3], None, [1,2,3])
77 test([[[1,'two'],3],'four',5], None, [1,'two',3,'four',5])
78
80 def test(list_, value):
81 result = sexpr_to_str(list_)
82 assert result == value, result
83 test([1,2,3], '[1,2,3]')
84 test((1,2,3), '(1,2,3)')
85 test(List([1,2,3]), 'List([1,2,3])')
86 class Foo(List): pass
87 test(Foo([1,2,(3,List([4]))]), 'Foo([1,2,(3,List([4]))])')
88
89
91
93
94 class Term(List): pass
95 class Factor(List): pass
96 class Expression(List): pass
97
98 expr = Delayed()
99 number = Digit()[1:,...] >> int
100
101 with Separator(Drop(Regexp(r'\s*'))):
102 term = number | '(' & expr & ')' > Term
103 muldiv = Any('*/')
104 factor = term & (muldiv & term)[:] > Factor
105 addsub = Any('+-')
106 expr += factor & (addsub & factor)[:] > Expression
107 line = expr & Eos()
108
109 ast = line.parse_string('1 + 2 * (3 + 4 - 5)')[0]
110 text = str(ast)
111 assert_str(text, """Expression
112 +- Factor
113 | `- Term
114 | `- 1
115 +- '+'
116 `- Factor
117 +- Term
118 | `- 2
119 +- '*'
120 `- Term
121 +- '('
122 +- Expression
123 | +- Factor
124 | | `- Term
125 | | `- 3
126 | +- '+'
127 | +- Factor
128 | | `- Term
129 | | `- 4
130 | +- '-'
131 | `- Factor
132 | `- Term
133 | `- 5
134 `- ')'""")
135
136
138
140 s = str(List())
141 assert s == 'List', s
142