vile / scheme / syntax_pattern.v
354 lines · 339 sloc · 11.74 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import reader
4
5struct SyntaxVariable {
6 identifier i32
7 depth int
8}
9
10@[heap]
11struct SyntaxPattern {
12 root i32
13mut:
14 variables []SyntaxVariable
15 indices map[i32]int
16 repeats map[i32][]int
17 // Populated only for a shared grammar. These validated compound nodes
18 // contain no captures, so matching them has no coordinate side effects.
19 constants &SyntaxPatternConstants = unsafe { nil }
20}
21
22struct PatternJob {
23 id i32
24 depth int
25 nesting int
26}
27
28fn (tree &SyntaxTree) compile_pattern(root i32, literals map[i32]SyntaxBinding) !SyntaxPattern {
29 first := tree.nodes[root]
30 if first.kind != .pair || tree.nodes[first.car].kind != .symbol {
31 return failure('syntax-rules pattern must begin with an identifier')
32 }
33 return tree.compile_pattern_body(root, first.cdr, literals, 'syntax-rules')
34}
35
36// Unlike syntax-rules, syntax-case matches its whole input: the root may be
37// an identifier, vector, empty list or atom, and a pair's head is significant.
38fn (tree &SyntaxTree) compile_case_pattern(root i32, literals map[i32]SyntaxBinding) !SyntaxPattern {
39 return tree.compile_pattern_body(root, root, literals, 'syntax-case')
40}
41
42fn (tree &SyntaxTree) compile_pattern_body(root i32, start i32, literals map[i32]SyntaxBinding, form string) !SyntaxPattern {
43 mut pattern := SyntaxPattern{ root: root }
44 mut jobs := [PatternJob{start, 0, 0}]
45 mut repeated := []i32{}
46 mut visits := map[u64]int{}
47 mut retained := false
48 defer { if !retained { unsafe { visits.free() } } }
49 for jobs.len > 0 {
50 job := jobs.pop()
51 if job.id < 0 {
52 // A postorder job carries the variable count before its subtree.
53 // Memoizing only variable-free subtrees lets the ordinary duplicate
54 // check catch a variable shared by two incoming occurrences.
55 if pattern.variables.len == job.depth { visits[u64(~job.id)] = job.nesting }
56 continue
57 }
58 if job.nesting > 512 { return failure('syntax pattern nesting limit exceeded') }
59 node := tree.nodes[job.id]
60 if !tree.unique_subtrees && node.kind in [.pair, .vector] {
61 if previous := visits[u64(job.id)] {
62 if previous >= job.nesting { continue }
63 }
64 jobs << PatternJob{~job.id, pattern.variables.len, job.nesting}
65 }
66 match node.kind {
67 .symbol {
68 if tree.ellipsis(job.id) {
69 return failure('misplaced ellipsis in ${form} pattern')
70 }
71 if node.car in literals || tree.wildcard(job.id) { continue }
72 if node.car in pattern.indices {
73 return failure('duplicate ${form} pattern variable')
74 }
75 pattern.indices[node.car] = pattern.variables.len
76 pattern.variables << SyntaxVariable{node.car, job.depth}
77 }
78 .pair {
79 mut cursor := job.id
80 mut repeat_pair := i32(-1)
81 for tree.nodes[cursor].kind == .pair {
82 pair := tree.nodes[cursor]
83 tail := tree.nodes[pair.cdr]
84 if tail.kind == .pair && tree.ellipsis(tail.car) {
85 if repeat_pair >= 0 {
86 return failure('only one repetition is allowed per pattern sequence')
87 }
88 repeat_pair = cursor
89 jobs << PatternJob{pair.car, job.depth + 1, job.nesting + 1}
90 repeated << pair.car
91 cursor = tail.cdr
92 } else {
93 jobs << PatternJob{pair.car, job.depth, job.nesting + 1}
94 cursor = pair.cdr
95 }
96 }
97 if tree.nodes[cursor].kind != .empty_list {
98 jobs << PatternJob{cursor, job.depth, job.nesting + 1}
99 }
100 }
101 .vector {
102 mut i := 0
103 mut repeated_at := -1
104 for i < int(node.cdr) {
105 body := tree.elements[node.car + i]
106 repeat := i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1])
107 if repeat {
108 if repeated_at >= 0 {
109 return failure('only one repetition is allowed per pattern sequence')
110 }
111 repeated_at = i
112 repeated << body
113 }
114 jobs << PatternJob{body, job.depth + int(repeat), job.nesting + 1}
115 i += if repeat { 2 } else { 1 }
116 }
117 }
118 else {}
119 }
120 }
121 for body in repeated {
122 if body !in pattern.repeats {
123 pattern.repeats[body] = tree.pattern_variables(body, pattern.indices)
124 }
125 }
126 if visits.len > 0 {
127 pattern.constants = &SyntaxPatternConstants{ nodes: visits }
128 retained = true
129 }
130 return pattern
131}
132
133fn (tree &SyntaxTree) pattern_variables(root i32, indices map[i32]int) []int {
134 mut result := []int{}
135 mut seen := map[int]bool{}
136 mut pending := [root]
137 mut visits := map[u64]int{}
138 defer { unsafe { visits.free() } }
139 for pending.len > 0 {
140 id := pending.pop()
141 node := tree.nodes[id]
142 if !tree.unique_subtrees && node.kind in [.pair, .vector] && syntax_grammar_seen(mut visits, id, 0, false, 0) { continue }
143 match node.kind {
144 .symbol {
145 if index := indices[node.car] {
146 if index !in seen {
147 seen[index] = true
148 result << index
149 }
150 }
151 }
152 .pair {
153 pending << node.car
154 pending << node.cdr
155 }
156 .vector {
157 for i in 0 .. int(node.cdr) { pending << tree.elements[node.car + i] }
158 }
159 else {}
160 }
161 }
162 return result
163}
164
165// Coordinate paths are interned once across pattern branches, so variables in
166// separate repeats can use the same template iteration coordinates. Captures
167// and dimension lengths have flat integer keys rather than per-element trees.
168struct SyntaxCaptures {
169mut:
170 // A variable's values occupy paths at its declared depth; dimensions occupy
171 // shorter prefixes. Those keys cannot overlap, so one scalar map holds both.
172 items map[u64]i32
173 paths map[u64]i32
174 next_path i32
175}
176
177fn syntax_capture_key(variable int, path i32) u64 {
178 return (u64(u32(variable)) << 32) | u64(u32(path))
179}
180
181fn (mut captures SyntaxCaptures) child_path(parent i32, index int) !i32 {
182 if index > 2147483647 { return failure('syntax match exceeds supported range') }
183 key := (u64(u32(parent)) << 32) | u64(u32(index))
184 if id := captures.paths[key] { return id }
185 if captures.next_path >= 2147483647 { return failure('syntax match exceeds supported range') }
186 captures.next_path++
187 id := captures.next_path
188 captures.paths[key] = id
189 return id
190}
191
192fn (mut b Builder) match_syntax_pattern(tree &SyntaxTree, pattern &SyntaxPattern, literals map[i32]SyntaxBinding, input reader.NodeId, mut captures SyntaxCaptures) !bool {
193 root := b.code.node(input)!
194 if root.kind != .pair || b.code.node(root.car)!.kind != .symbol { return false }
195 return b.match_pattern_node(tree, pattern, literals, tree.nodes[pattern.root].cdr, root.cdr, 0, mut captures)
196}
197
198// Each top-level invocation owns its table. Input IDs and pattern IDs are
199// meaningful only within that invocation; no result survives a binding change.
200fn (mut b Builder) match_pattern_node(tree &SyntaxTree, pattern &SyntaxPattern, literals map[i32]SyntaxBinding, id i32, input reader.NodeId, path i32, mut captures SyntaxCaptures) !bool {
201 if isnil(pattern.constants) {
202 return b.match_pattern_body[PlainSyntaxMatch](tree, pattern, literals, id, input, path, mut captures, unsafe { nil })
203 }
204 mut memo := SyntaxMatchMemo{}
205 defer { unsafe { memo.completed.free() } }
206 return b.match_pattern_cached[SharedSyntaxMatch](tree, pattern, literals, id, input, path, mut captures, &memo)
207}
208
209@[inline]
210fn (mut b Builder) match_pattern_cached[M](tree &SyntaxTree, pattern &SyntaxPattern, literals map[i32]SyntaxBinding, id i32, input reader.NodeId, path i32, mut captures SyntaxCaptures, cache &SyntaxMatchMemo) !bool {
211 $if M is SharedSyntaxMatch {
212 mut memo := unsafe { cache }
213 if u64(u32(id)) in pattern.constants.nodes {
214 key := syntax_match_key(id, i32(input))
215 if result := memo.completed[key] { return result }
216 result := b.match_pattern_body[M](tree, pattern, literals, id, input, path, mut captures, cache)!
217 memo.completed[key] = result
218 return result
219 }
220 }
221 return b.match_pattern_body[M](tree, pattern, literals, id, input, path, mut captures, cache)
222}
223
224fn (mut b Builder) match_pattern_body[M](tree &SyntaxTree, pattern &SyntaxPattern, literals map[i32]SyntaxBinding, id i32, input reader.NodeId, path i32, mut captures SyntaxCaptures, cache &SyntaxMatchMemo) !bool {
225 node := tree.nodes[id]
226 match node.kind {
227 .symbol {
228 if literal := literals[node.car] {
229 if b.code.node(input)!.kind != .symbol { return false }
230 return same_syntax_binding(b.current_syntax_binding(literal), b.resolve_binding(b.code.name(input)!))
231 }
232 if tree.wildcard(id) { return true }
233 variable := pattern.indices[node.car] or { return failure('invalid compiled pattern variable') }
234 captures.items[syntax_capture_key(variable, path)] = i32(input)
235 return true
236 }
237 .pair {
238 mut cursor := id
239 mut source := input
240 for tree.nodes[cursor].kind == .pair {
241 pair := tree.nodes[cursor]
242 tail := tree.nodes[pair.cdr]
243 if tail.kind == .pair && tree.ellipsis(tail.car) {
244 if !isnil(b.code.graphs) { b.code.require_finite_spine(source)! }
245 variables := pattern.repeats[pair.car]
246 // Trailing repeats stream once through the input. Only a fixed
247 // suffix needs a preliminary count to reserve its elements.
248 mut suffix := 0
249 mut remaining_pattern := tail.cdr
250 for tree.nodes[remaining_pattern].kind == .pair {
251 suffix++
252 remaining_pattern = tree.nodes[remaining_pattern].cdr
253 }
254 mut remaining := -1
255 if suffix > 0 {
256 mut probe := source
257 mut available := 0
258 for {
259 item := b.code.node(probe)!
260 if item.kind != .pair { break }
261 available++
262 probe = item.cdr
263 }
264 if available < suffix { return false }
265 remaining = available - suffix
266 }
267 mut count := 0
268 for remaining != 0 {
269 item := b.code.node(source)!
270 if item.kind != .pair { break }
271 child := if variables.len > 0 {
272 captures.child_path(path, count)!
273 } else {
274 path
275 }
276 if !b.match_pattern_cached[M](tree, pattern, literals, pair.car, item.car, child, mut captures, cache)! {
277 return false
278 }
279 source = item.cdr
280 count++
281 if remaining > 0 { remaining-- }
282 }
283 for variable in variables {
284 captures.items[syntax_capture_key(variable, path)] = i32(count)
285 }
286 cursor = tail.cdr
287 continue
288 }
289 item := b.code.node(source)!
290 if item.kind != .pair { return false }
291 if !b.match_pattern_cached[M](tree, pattern, literals, pair.car, item.car, path, mut captures, cache)! {
292 return false
293 }
294 cursor = pair.cdr
295 source = item.cdr
296 }
297 return b.match_pattern_cached[M](tree, pattern, literals, cursor, source, path, mut captures, cache)
298 }
299 .vector {
300 source := b.code.node(input)!
301 if source.kind != .vector { return false }
302 count := int(node.cdr)
303 mut repeated_at := -1
304 for position in 1 .. count {
305 if tree.ellipsis(tree.elements[node.car + position]) {
306 repeated_at = position - 1
307 break
308 }
309 }
310 fixed := count - if repeated_at >= 0 { 2 } else { 0 }
311 if source.count < fixed || (repeated_at < 0 && source.count != fixed) { return false }
312 width := source.count - fixed
313 mut index := 0
314 for index < count {
315 body := tree.elements[node.car + index]
316 if index == repeated_at {
317 variables := pattern.repeats[body]
318 for offset in 0 .. width {
319 child := if variables.len > 0 {
320 captures.child_path(path, offset)!
321 } else {
322 path
323 }
324 if !b.match_pattern_cached[M](tree, pattern, literals, body, b.code.vector_at(input, index + offset)!, child, mut captures, cache)! {
325 return false
326 }
327 }
328 for variable in variables {
329 captures.items[syntax_capture_key(variable, path)] = i32(width)
330 }
331 index += 2
332 } else {
333 position := if repeated_at >= 0 && index > repeated_at {
334 index - 2 + width
335 } else {
336 index
337 }
338 if !b.match_pattern_cached[M](tree, pattern, literals, body, b.code.vector_at(input, position)!, path, mut captures, cache)! {
339 return false
340 }
341 index++
342 }
343 }
344 return true
345 }
346 .empty_list { return b.code.node(input)!.kind == .empty_list }
347 else {
348 if b.code.node(input)!.kind != node.kind { return false }
349 expected := tree.values[node.car]
350 actual := b.code.datum(input)!
351 return syntax_pattern_atom_equal(expected, actual)
352 }
353 }
354}
355