@@ -3,7 +3,7 @@ import type { Document } from '../doc/Document.ts'
3
3
import type { FlowScalar } from '../parse/cst.ts'
4
4
import type { StringifyContext } from '../stringify/stringify.ts'
5
5
import { visit } from '../visit.ts'
6
- import { ALIAS , isAlias , isCollection , isPair } from './identity.ts'
6
+ import { ALIAS , hasAnchor , isAlias , isCollection , isPair } from './identity.ts'
7
7
import type { Node , Range } from './Node.ts'
8
8
import { NodeBase } from './Node.ts'
9
9
import type { Scalar } from './Scalar.ts'
@@ -38,21 +38,36 @@ export class Alias extends NodeBase {
38
38
* Resolve the value of this alias within `doc`, finding the last
39
39
* instance of the `source` anchor before this node.
40
40
*/
41
- resolve ( doc : Document ) : Scalar | YAMLMap | YAMLSeq | undefined {
41
+ resolve (
42
+ doc : Document ,
43
+ ctx ?: ToJSContext
44
+ ) : Scalar | YAMLMap | YAMLSeq | undefined {
45
+ let nodes : Node [ ]
46
+ if ( ctx ?. aliasResolveCache ) {
47
+ nodes = ctx . aliasResolveCache
48
+ } else {
49
+ nodes = [ ]
50
+ visit ( doc , {
51
+ Node : ( _key : unknown , node : Node ) => {
52
+ if ( isAlias ( node ) || hasAnchor ( node ) ) nodes . push ( node )
53
+ }
54
+ } )
55
+ if ( ctx ) ctx . aliasResolveCache = nodes
56
+ }
57
+
42
58
let found : Scalar | YAMLMap | YAMLSeq | undefined = undefined
43
- visit ( doc , {
44
- Node : ( _key : unknown , node : Node ) => {
45
- if ( node === this ) return visit . BREAK
46
- if ( node . anchor === this . source ) found = node
47
- }
48
- } )
59
+ for ( const node of nodes ) {
60
+ if ( node === this ) break
61
+ if ( node . anchor === this . source ) found = node
62
+ }
63
+
49
64
return found
50
65
}
51
66
52
67
toJSON ( _arg ?: unknown , ctx ?: ToJSContext ) : unknown {
53
68
if ( ! ctx ) return { source : this . source }
54
69
const { anchors, doc, maxAliasCount } = ctx
55
- const source = this . resolve ( doc )
70
+ const source = this . resolve ( doc , ctx )
56
71
if ( ! source ) {
57
72
const msg = `Unresolved alias (the anchor must be set before the alias): ${ this . source } `
58
73
throw new ReferenceError ( msg )
0 commit comments