module scheme import reader struct SyntaxVariable { identifier i32 depth int } @[heap] struct SyntaxPattern { root i32 mut: variables []SyntaxVariable indices map[i32]int repeats map[i32][]int // Populated only for a shared grammar. These validated compound nodes // contain no captures, so matching them has no coordinate side effects. constants &SyntaxPatternConstants = unsafe { nil } } struct PatternJob { id i32 depth int nesting int } fn (tree &SyntaxTree) compile_pattern(root i32, literals map[i32]SyntaxBinding) !SyntaxPattern { first := tree.nodes[root] if first.kind != .pair || tree.nodes[first.car].kind != .symbol { return failure('syntax-rules pattern must begin with an identifier') } return tree.compile_pattern_body(root, first.cdr, literals, 'syntax-rules') } // Unlike syntax-rules, syntax-case matches its whole input: the root may be // an identifier, vector, empty list or atom, and a pair's head is significant. fn (tree &SyntaxTree) compile_case_pattern(root i32, literals map[i32]SyntaxBinding) !SyntaxPattern { return tree.compile_pattern_body(root, root, literals, 'syntax-case') } fn (tree &SyntaxTree) compile_pattern_body(root i32, start i32, literals map[i32]SyntaxBinding, form string) !SyntaxPattern { mut pattern := SyntaxPattern{ root: root } mut jobs := [PatternJob{start, 0, 0}] mut repeated := []i32{} mut visits := map[u64]int{} mut retained := false defer { if !retained { unsafe { visits.free() } } } for jobs.len > 0 { job := jobs.pop() if job.id < 0 { // A postorder job carries the variable count before its subtree. // Memoizing only variable-free subtrees lets the ordinary duplicate // check catch a variable shared by two incoming occurrences. if pattern.variables.len == job.depth { visits[u64(~job.id)] = job.nesting } continue } if job.nesting > 512 { return failure('syntax pattern nesting limit exceeded') } node := tree.nodes[job.id] if !tree.unique_subtrees && node.kind in [.pair, .vector] { if previous := visits[u64(job.id)] { if previous >= job.nesting { continue } } jobs << PatternJob{~job.id, pattern.variables.len, job.nesting} } match node.kind { .symbol { if tree.ellipsis(job.id) { return failure('misplaced ellipsis in ${form} pattern') } if node.car in literals || tree.wildcard(job.id) { continue } if node.car in pattern.indices { return failure('duplicate ${form} pattern variable') } pattern.indices[node.car] = pattern.variables.len pattern.variables << SyntaxVariable{node.car, job.depth} } .pair { mut cursor := job.id mut repeat_pair := i32(-1) for tree.nodes[cursor].kind == .pair { pair := tree.nodes[cursor] tail := tree.nodes[pair.cdr] if tail.kind == .pair && tree.ellipsis(tail.car) { if repeat_pair >= 0 { return failure('only one repetition is allowed per pattern sequence') } repeat_pair = cursor jobs << PatternJob{pair.car, job.depth + 1, job.nesting + 1} repeated << pair.car cursor = tail.cdr } else { jobs << PatternJob{pair.car, job.depth, job.nesting + 1} cursor = pair.cdr } } if tree.nodes[cursor].kind != .empty_list { jobs << PatternJob{cursor, job.depth, job.nesting + 1} } } .vector { mut i := 0 mut repeated_at := -1 for i < int(node.cdr) { body := tree.elements[node.car + i] repeat := i + 1 < int(node.cdr) && tree.ellipsis(tree.elements[node.car + i + 1]) if repeat { if repeated_at >= 0 { return failure('only one repetition is allowed per pattern sequence') } repeated_at = i repeated << body } jobs << PatternJob{body, job.depth + int(repeat), job.nesting + 1} i += if repeat { 2 } else { 1 } } } else {} } } for body in repeated { if body !in pattern.repeats { pattern.repeats[body] = tree.pattern_variables(body, pattern.indices) } } if visits.len > 0 { pattern.constants = &SyntaxPatternConstants{ nodes: visits } retained = true } return pattern } fn (tree &SyntaxTree) pattern_variables(root i32, indices map[i32]int) []int { mut result := []int{} mut seen := map[int]bool{} mut pending := [root] mut visits := map[u64]int{} defer { unsafe { visits.free() } } for pending.len > 0 { id := pending.pop() node := tree.nodes[id] if !tree.unique_subtrees && node.kind in [.pair, .vector] && syntax_grammar_seen(mut visits, id, 0, false, 0) { continue } match node.kind { .symbol { if index := indices[node.car] { if index !in seen { seen[index] = true result << index } } } .pair { pending << node.car pending << node.cdr } .vector { for i in 0 .. int(node.cdr) { pending << tree.elements[node.car + i] } } else {} } } return result } // Coordinate paths are interned once across pattern branches, so variables in // separate repeats can use the same template iteration coordinates. Captures // and dimension lengths have flat integer keys rather than per-element trees. struct SyntaxCaptures { mut: // A variable's values occupy paths at its declared depth; dimensions occupy // shorter prefixes. Those keys cannot overlap, so one scalar map holds both. items map[u64]i32 paths map[u64]i32 next_path i32 } fn syntax_capture_key(variable int, path i32) u64 { return (u64(u32(variable)) << 32) | u64(u32(path)) } fn (mut captures SyntaxCaptures) child_path(parent i32, index int) !i32 { if index > 2147483647 { return failure('syntax match exceeds supported range') } key := (u64(u32(parent)) << 32) | u64(u32(index)) if id := captures.paths[key] { return id } if captures.next_path >= 2147483647 { return failure('syntax match exceeds supported range') } captures.next_path++ id := captures.next_path captures.paths[key] = id return id } fn (mut b Builder) match_syntax_pattern(tree &SyntaxTree, pattern &SyntaxPattern, literals map[i32]SyntaxBinding, input reader.NodeId, mut captures SyntaxCaptures) !bool { root := b.code.node(input)! if root.kind != .pair || b.code.node(root.car)!.kind != .symbol { return false } return b.match_pattern_node(tree, pattern, literals, tree.nodes[pattern.root].cdr, root.cdr, 0, mut captures) } // Each top-level invocation owns its table. Input IDs and pattern IDs are // meaningful only within that invocation; no result survives a binding change. fn (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 { if isnil(pattern.constants) { return b.match_pattern_body[PlainSyntaxMatch](tree, pattern, literals, id, input, path, mut captures, unsafe { nil }) } mut memo := SyntaxMatchMemo{} defer { unsafe { memo.completed.free() } } return b.match_pattern_cached[SharedSyntaxMatch](tree, pattern, literals, id, input, path, mut captures, &memo) } @[inline] fn (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 { $if M is SharedSyntaxMatch { mut memo := unsafe { cache } if u64(u32(id)) in pattern.constants.nodes { key := syntax_match_key(id, i32(input)) if result := memo.completed[key] { return result } result := b.match_pattern_body[M](tree, pattern, literals, id, input, path, mut captures, cache)! memo.completed[key] = result return result } } return b.match_pattern_body[M](tree, pattern, literals, id, input, path, mut captures, cache) } fn (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 { node := tree.nodes[id] match node.kind { .symbol { if literal := literals[node.car] { if b.code.node(input)!.kind != .symbol { return false } return same_syntax_binding(b.current_syntax_binding(literal), b.resolve_binding(b.code.name(input)!)) } if tree.wildcard(id) { return true } variable := pattern.indices[node.car] or { return failure('invalid compiled pattern variable') } captures.items[syntax_capture_key(variable, path)] = i32(input) return true } .pair { mut cursor := id mut source := input for tree.nodes[cursor].kind == .pair { pair := tree.nodes[cursor] tail := tree.nodes[pair.cdr] if tail.kind == .pair && tree.ellipsis(tail.car) { if !isnil(b.code.graphs) { b.code.require_finite_spine(source)! } variables := pattern.repeats[pair.car] // Trailing repeats stream once through the input. Only a fixed // suffix needs a preliminary count to reserve its elements. mut suffix := 0 mut remaining_pattern := tail.cdr for tree.nodes[remaining_pattern].kind == .pair { suffix++ remaining_pattern = tree.nodes[remaining_pattern].cdr } mut remaining := -1 if suffix > 0 { mut probe := source mut available := 0 for { item := b.code.node(probe)! if item.kind != .pair { break } available++ probe = item.cdr } if available < suffix { return false } remaining = available - suffix } mut count := 0 for remaining != 0 { item := b.code.node(source)! if item.kind != .pair { break } child := if variables.len > 0 { captures.child_path(path, count)! } else { path } if !b.match_pattern_cached[M](tree, pattern, literals, pair.car, item.car, child, mut captures, cache)! { return false } source = item.cdr count++ if remaining > 0 { remaining-- } } for variable in variables { captures.items[syntax_capture_key(variable, path)] = i32(count) } cursor = tail.cdr continue } item := b.code.node(source)! if item.kind != .pair { return false } if !b.match_pattern_cached[M](tree, pattern, literals, pair.car, item.car, path, mut captures, cache)! { return false } cursor = pair.cdr source = item.cdr } return b.match_pattern_cached[M](tree, pattern, literals, cursor, source, path, mut captures, cache) } .vector { source := b.code.node(input)! if source.kind != .vector { return false } count := int(node.cdr) mut repeated_at := -1 for position in 1 .. count { if tree.ellipsis(tree.elements[node.car + position]) { repeated_at = position - 1 break } } fixed := count - if repeated_at >= 0 { 2 } else { 0 } if source.count < fixed || (repeated_at < 0 && source.count != fixed) { return false } width := source.count - fixed mut index := 0 for index < count { body := tree.elements[node.car + index] if index == repeated_at { variables := pattern.repeats[body] for offset in 0 .. width { child := if variables.len > 0 { captures.child_path(path, offset)! } else { path } if !b.match_pattern_cached[M](tree, pattern, literals, body, b.code.vector_at(input, index + offset)!, child, mut captures, cache)! { return false } } for variable in variables { captures.items[syntax_capture_key(variable, path)] = i32(width) } index += 2 } else { position := if repeated_at >= 0 && index > repeated_at { index - 2 + width } else { index } if !b.match_pattern_cached[M](tree, pattern, literals, body, b.code.vector_at(input, position)!, path, mut captures, cache)! { return false } index++ } } return true } .empty_list { return b.code.node(input)!.kind == .empty_list } else { if b.code.node(input)!.kind != node.kind { return false } expected := tree.values[node.car] actual := b.code.datum(input)! return syntax_pattern_atom_equal(expected, actual) } } }