MCPcopy Create free account
hub / github.com/anomalyco/opencode / walk

Function walk

packages/core/src/effect/layer-node.ts:171–209  ·  view source on GitHub ↗
(
  root: AnyNode,
  visit: Visit<Result>,
  options: {
    readonly cache?: Map<AnyNode, Result>
    readonly resolve?: (node: AnyNode) => AnyNode
    readonly detectCycles?: boolean
  } = {},
)

Source from the content-addressed store, hash-verified

169}
170
171function walk<Result>(
172 root: AnyNode,
173 visit: Visit<Result>,
174 options: {
175 readonly cache?: Map<AnyNode, Result>
176 readonly resolve?: (node: AnyNode) => AnyNode
177 readonly detectCycles?: boolean
178 } = {},
179) {
180 const cache = options.cache ?? new Map<AnyNode, Result>()
181 const visiting = new Set<AnyNode>()
182 const stack: AnyNode[] = []
183
184 const recur = (node: AnyNode): Result => {
185 const target = options.resolve?.(node) ?? node
186 const cached = cache.get(target)
187 if (cached !== undefined || cache.has(target)) return cached!
188
189 if (options.detectCycles !== false && visiting.has(target)) {
190 const start = stack.indexOf(target)
191 throw new Error(
192 `Cycle detected in layer tree: ${[...stack.slice(start), target].map((item) => item.name).join(" -> ")}`,
193 )
194 }
195
196 visiting.add(target)
197 stack.push(target)
198 try {
199 const result = visit(target, { cache, visit: recur })
200 if (!cache.has(target)) cache.set(target, result)
201 return result
202 } finally {
203 stack.pop()
204 visiting.delete(target)
205 }
206 }
207
208 return recur(root)
209}
210
211export function hoist<A, E, T extends Tag, const Items extends Replacements = readonly []>(
212 root: Node<A, E, any>,

Callers 3

hoistFunction · 0.70
compileNodeFunction · 0.70
hasUnboundFunction · 0.70

Calls 1

recurFunction · 0.85

Tested by

no test coverage detected