UNPKG

2.26 kBTypeScriptView Raw
1import type { CollectionItem, Document } from './cst.js';
2export type VisitPath = readonly ['key' | 'value', number][];
3export type Visitor = (item: CollectionItem, path: VisitPath) => number | symbol | Visitor | void;
4/**
5 * Apply a visitor to a CST document or item.
6 *
7 * Walks through the tree (depth-first) starting from the root, calling a
8 * `visitor` function with two arguments when entering each item:
9 * - `item`: The current item, which included the following members:
10 * - `start: SourceToken[]` – Source tokens before the key or value,
11 * possibly including its anchor or tag.
12 * - `key?: Token | null` – Set for pair values. May then be `null`, if
13 * the key before the `:` separator is empty.
14 * - `sep?: SourceToken[]` – Source tokens between the key and the value,
15 * which should include the `:` map value indicator if `value` is set.
16 * - `value?: Token` – The value of a sequence item, or of a map pair.
17 * - `path`: The steps from the root to the current node, as an array of
18 * `['key' | 'value', number]` tuples.
19 *
20 * The return value of the visitor may be used to control the traversal:
21 * - `undefined` (default): Do nothing and continue
22 * - `visit.SKIP`: Do not visit the children of this token, continue with
23 * next sibling
24 * - `visit.BREAK`: Terminate traversal completely
25 * - `visit.REMOVE`: Remove the current item, then continue with the next one
26 * - `number`: Set the index of the next step. This is useful especially if
27 * the index of the current token has changed.
28 * - `function`: Define the next visitor for this item. After the original
29 * visitor is called on item entry, next visitors are called after handling
30 * a non-empty `key` and when exiting the item.
31 */
32export declare function visit(cst: Document | CollectionItem, visitor: Visitor): void;
33export declare namespace visit {
34 var BREAK: symbol;
35 var SKIP: symbol;
36 var REMOVE: symbol;
37 var itemAtPath: (cst: Document | CollectionItem, path: VisitPath) => CollectionItem | undefined;
38 var parentCollection: (cst: Document | CollectionItem, path: VisitPath) => import("./cst.js").BlockMap | import("./cst.js").BlockSequence | import("./cst.js").FlowCollection;
39}