Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/errors/src/codes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export const CODAMA_ERROR__VISITORS__INSTRUCTION_ENUM_ARGUMENT_NOT_FOUND = 12000
export const CODAMA_ERROR__VISITORS__CANNOT_FLATTEN_STRUCT_WITH_CONFLICTING_ATTRIBUTES = 1200010;
export const CODAMA_ERROR__VISITORS__RENDER_MAP_KEY_NOT_FOUND = 1200011;
export const CODAMA_ERROR__VISITORS__CANNOT_REMOVE_LAST_PATH_IN_NODE_STACK = 1200012;
export const CODAMA_ERROR__VISITORS__INVALID_PROVIDED_VALUE = 1200013;

// Anchor-related errors.
// Reserve error codes in the range [2100000-2100999].
Expand Down Expand Up @@ -165,4 +166,5 @@ export type CodamaErrorCode =
| typeof CODAMA_ERROR__VISITORS__INVALID_INSTRUCTION_DEFAULT_VALUE_DEPENDENCY
| typeof CODAMA_ERROR__VISITORS__INVALID_NUMBER_WRAPPER
| typeof CODAMA_ERROR__VISITORS__INVALID_PDA_SEED_VALUES
| typeof CODAMA_ERROR__VISITORS__INVALID_PROVIDED_VALUE
| typeof CODAMA_ERROR__VISITORS__RENDER_MAP_KEY_NOT_FOUND;
8 changes: 8 additions & 0 deletions packages/errors/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
PdaNode,
PdaSeedValueNode,
ProgramNode,
ProvidedNode,
StructFieldTypeNode,
} from '@codama/node-types';

Expand Down Expand Up @@ -77,6 +78,7 @@ import {
CODAMA_ERROR__VISITORS__INVALID_INSTRUCTION_DEFAULT_VALUE_DEPENDENCY,
CODAMA_ERROR__VISITORS__INVALID_NUMBER_WRAPPER,
CODAMA_ERROR__VISITORS__INVALID_PDA_SEED_VALUES,
CODAMA_ERROR__VISITORS__INVALID_PROVIDED_VALUE,
CODAMA_ERROR__VISITORS__RENDER_MAP_KEY_NOT_FOUND,
CodamaErrorCode,
} from './codes';
Expand Down Expand Up @@ -315,6 +317,12 @@ export type CodamaErrorContext = DefaultUnspecifiedErrorContextToUndefined<{
pda: PdaNode;
pdaName: IdentifierString;
};
[CODAMA_ERROR__VISITORS__INVALID_PROVIDED_VALUE]: {
expectedKinds: NodeKind[];
key: IdentifierString;
provider: ProvidedNode;
providedKind: NodeKind;
};
[CODAMA_ERROR__VISITORS__RENDER_MAP_KEY_NOT_FOUND]: {
key: string;
};
Expand Down
3 changes: 3 additions & 0 deletions packages/errors/src/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import {
CODAMA_ERROR__VISITORS__INVALID_INSTRUCTION_DEFAULT_VALUE_DEPENDENCY,
CODAMA_ERROR__VISITORS__INVALID_NUMBER_WRAPPER,
CODAMA_ERROR__VISITORS__INVALID_PDA_SEED_VALUES,
CODAMA_ERROR__VISITORS__INVALID_PROVIDED_VALUE,
CODAMA_ERROR__VISITORS__RENDER_MAP_KEY_NOT_FOUND,
CodamaErrorCode,
} from './codes';
Expand Down Expand Up @@ -151,5 +152,7 @@ export const CodamaErrorMessages: Readonly<{
[CODAMA_ERROR__VISITORS__INVALID_NUMBER_WRAPPER]: 'Invalid number wrapper kind [$wrapper].',
[CODAMA_ERROR__VISITORS__INVALID_PDA_SEED_VALUES]:
'Invalid seed values for PDA [$pdaName] in instruction [$instructionName].',
[CODAMA_ERROR__VISITORS__INVALID_PROVIDED_VALUE]:
'The value provided for [$key] is a [$providedKind], expected one of [$expectedKinds].',
[CODAMA_ERROR__VISITORS__RENDER_MAP_KEY_NOT_FOUND]: 'Cannot find key [$key] in RenderMap.',
};
12 changes: 12 additions & 0 deletions packages/nodes/src/TextNode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { TextNode } from '@codama/node-types';

/**
* Read the plain-string content of a `string | TextNode` value.
*
* `docs`, `instructionStatusNode.message`, display labels and intents are
* all `string | TextNode` — a plain string or the rich {@link textNode}
* arm. This returns the underlying text for either form.
*/
export function getTextNodeContent(value: string | TextNode): string {
return typeof value === 'string' ? value : value.content;
}
1 change: 1 addition & 0 deletions packages/nodes/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export * from './EnumTypeNode';
export * from './InstructionNode';
export * from './Node';
export * from './ProgramNode';
export * from './TextNode';
export * from './TypeNode';

// Legacy plural-noun aliases preserved for API stability. Each maps to
Expand Down
18 changes: 3 additions & 15 deletions packages/visitors-core/src/LinkableDictionary.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { CODAMA_ERROR__LINKED_NODE_NOT_FOUND, CodamaError } from '@codama/errors';
import {
AccountNode,
CamelCaseString,
DefinedTypeNode,
IdentifierString,
InstructionAccountNode,
InstructionArgumentNode,
InstructionNode,
isNode,
LinkNode,
Expand All @@ -25,7 +24,6 @@ export type LinkableNode =
| AccountNode
| DefinedTypeNode
| InstructionAccountNode
| InstructionArgumentNode
| InstructionNode
| PdaNode
| ProgramNode;
Expand All @@ -34,7 +32,6 @@ export const LINKABLE_NODES: LinkableNode['kind'][] = [
'accountNode',
'definedTypeNode',
'instructionAccountNode',
'instructionArgumentNode',
'instructionNode',
'pdaNode',
'programNode',
Expand All @@ -44,7 +41,6 @@ export type GetLinkableFromLinkNode<TLinkNode extends LinkNode> = {
accountLinkNode: AccountNode;
definedTypeLinkNode: DefinedTypeNode;
instructionAccountLinkNode: InstructionAccountNode;
instructionArgumentLinkNode: InstructionArgumentNode;
instructionLinkNode: InstructionNode;
pdaLinkNode: PdaNode;
programLinkNode: ProgramNode;
Expand All @@ -60,7 +56,6 @@ type ProgramDictionary = {

type InstructionDictionary = {
accounts: Map<string, NodePath<InstructionAccountNode>>;
arguments: Map<string, NodePath<InstructionArgumentNode>>;
instruction: NodePath<InstructionNode>;
};

Expand All @@ -81,8 +76,6 @@ export class LinkableDictionary {
programDictionary.pdas.set(linkableNode.identifier, linkablePath);
} else if (instructionDictionary && isNodePath(linkablePath, 'instructionAccountNode')) {
instructionDictionary.accounts.set(linkableNode.identifier, linkablePath);
} else if (instructionDictionary && isNodePath(linkablePath, 'instructionArgumentNode')) {
instructionDictionary.arguments.set(linkableNode.identifier, linkablePath);
}

return this;
Expand Down Expand Up @@ -121,8 +114,6 @@ export class LinkableDictionary {
return programDictionary.definedTypes.get(linkNode.identifier) as LinkablePath;
} else if (isNode(linkNode, 'instructionAccountLinkNode')) {
return instructionDictionary?.accounts.get(linkNode.identifier) as LinkablePath;
} else if (isNode(linkNode, 'instructionArgumentLinkNode')) {
return instructionDictionary?.arguments.get(linkNode.name) as LinkablePath;
} else if (isNode(linkNode, 'instructionLinkNode')) {
return instructionDictionary?.instruction as LinkablePath;
} else if (isNode(linkNode, 'pdaLinkNode')) {
Expand Down Expand Up @@ -155,8 +146,6 @@ export class LinkableDictionary {
return programDictionary.definedTypes.has(linkNode.identifier);
} else if (isNode(linkNode, 'instructionAccountLinkNode')) {
return !!instructionDictionary && instructionDictionary.accounts.has(linkNode.identifier);
} else if (isNode(linkNode, 'instructionArgumentLinkNode')) {
return !!instructionDictionary && instructionDictionary.arguments.has(linkNode.name);
} else if (isNode(linkNode, 'instructionLinkNode')) {
return programDictionary.instructions.has(linkNode.identifier);
} else if (isNode(linkNode, 'pdaLinkNode')) {
Expand Down Expand Up @@ -202,7 +191,6 @@ export class LinkableDictionary {
if (!instructionDictionary) {
instructionDictionary = {
accounts: new Map(),
arguments: new Map(),
instruction: getNodePathUntilLastNode(linkablePath, 'instructionNode')!,
};
programDictionary.instructions.set(instructionNode.identifier, instructionDictionary);
Expand All @@ -213,7 +201,7 @@ export class LinkableDictionary {

private getProgramDictionary(linkPath: NodePath<LinkNode>): ProgramDictionary | undefined {
const linkNode = getLastNodeFromPath(linkPath);
let programName: CamelCaseString | undefined = undefined;
let programName: IdentifierString | undefined = undefined;
if (isNode(linkNode, 'programLinkNode')) {
programName = linkNode.identifier;
} else if ('program' in linkNode) {
Expand All @@ -231,7 +219,7 @@ export class LinkableDictionary {
linkPath: NodePath<LinkNode>,
): InstructionDictionary | undefined {
const linkNode = getLastNodeFromPath(linkPath);
let instructionName: CamelCaseString | undefined = undefined;
let instructionName: IdentifierString | undefined = undefined;
if (isNode(linkNode, 'instructionLinkNode')) {
instructionName = linkNode.identifier;
} else if ('instruction' in linkNode) {
Expand Down
12 changes: 4 additions & 8 deletions packages/visitors-core/src/NodeSelector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ export type NodeSelector = NodeSelectorFunction | NodeSelectorPath;
/**
* A string that can be used to select a node in a Codama tree.
* - `*` matches any node.
* - `someText` matches the name of a node, if any.
* - `someText` matches the identifier of a node, if any.
* - `[someNode]` matches a node of the given kind.
* - `[someNode|someOtherNode]` matches a node with any of the given kind.
* - `[someNode]someText` matches both the kind and the name of a node.
* - `[someNode]someText` matches both the kind and the identifier of a node.
* - `a.b.c` matches a node `c` such that its ancestors contains `a` and `b` in order (but not necessarily subsequent).
*/
export type NodeSelectorPath = string;
Expand All @@ -32,12 +32,8 @@ export const getNodeSelectorFunction = (selector: NodeSelector): NodeSelectorFun
return false;
}

// Check names.
// NOTE: v2 identifiers are no longer camelCase-normalised, so comparing a
// camelCased selector against `node.identifier` is not quite right — the
// case-fold/underscore-strip comparison is a follow-up. Cast to `string`
// for now to keep the mechanical rename compiling without changing behaviour.
if (name && (!('identifier' in node) || camelCase(name) !== (node.identifier as string))) {
// Check identifiers.
if (name && (!('identifier' in node) || node.identifier !== name)) {
return false;
}

Expand Down
146 changes: 146 additions & 0 deletions packages/visitors-core/src/ProvidedScope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { CODAMA_ERROR__VISITORS__INVALID_PROVIDED_VALUE, CodamaError } from '@codama/errors';
import {
assertIsNode,
type GetNodeFromKind,
type IdentifierString,
type InjectedValueNode,
isNode,
type Node,
type NodeKind,
type ProvidedNode,
} from '@codama/nodes';

import { bottomUpTransformerVisitor } from './bottomUpTransformerVisitor';
import { visit } from './visitor';

/** A node an injection resolved to, with the frame depth its own injections resolve against. */
type Resolution = { depth: number; node: Node; provider?: ProvidedNode };

/**
* The lexical scope of `providedNode`s visible at a point of the tree,
* used to resolve `injectedValueNode`s.
*
* Each `instructionNode` carrying `provides` contributes one frame (the
* only host of `provides` today). Resolution is lexical: the innermost
* frame providing a key wins and outer frames remain visible — e.g. a
* sub-instruction may shadow a key provided by its parent. Frames are
* independent of the {@link NodeStack}, so following links (e.g. into a
* defined type) keeps the frames of the consuming instruction in scope.
*
* @see {@link recordProvidedScopeVisitor} to fill a scope during a traversal.
*/
export class ProvidedScope {
private readonly frames: (readonly ProvidedNode[])[];

constructor(...frames: readonly (readonly ProvidedNode[])[]) {
this.frames = frames.map(frame => [...frame]);
}

/** Open a new innermost frame with the given providers. */
public push(provides: readonly ProvidedNode[]): void {
this.frames.push([...provides]);
}

/** Close the innermost frame. */
public pop(): void {
this.frames.pop();
}

/** The innermost provider for the given key, if any. */
public get(key: IdentifierString): ProvidedNode | undefined {
return this.find(key, this.frames.length)?.provider;
}

/**
* Resolve every `injectedValueNode` within `node` — itself included —
* and return the result, which never contains an injection.
*
* An injection resolves to the innermost provided node for its key. A
* provided node is resolved against the frames outside the one
* providing it, so a provider may re-inject its own key. The
* injection's `fallback` is used when no frame provides the key, or
* when the provided chain dead-ends. Resolution is all-or-nothing: if
* any injection within `node` resolves to nothing, `undefined` is
* returned rather than a partially resolved value. A `node` containing
* no injection is returned as-is.
*
* The root result must be one of `kinds`: a provided node that is not
* throws `CODAMA_ERROR__VISITORS__INVALID_PROVIDED_VALUE`, any other
* node throws `CODAMA_ERROR__UNEXPECTED_NODE_KIND`. Nested
* injections are checked by the node that holds them.
*/
public resolve<TKind extends NodeKind>(
node: Node,
options: { kinds: TKind[] },
): Exclude<GetNodeFromKind<TKind>, InjectedValueNode> | undefined {
const depth = this.frames.length;
const resolution = isNode(node, 'injectedValueNode') ? this.lookup(node, depth) : { depth, node };
if (!resolution) return undefined;
if (!isNode(resolution.node, options.kinds)) {
if (resolution.provider) {
throw new CodamaError(CODAMA_ERROR__VISITORS__INVALID_PROVIDED_VALUE, {
expectedKinds: options.kinds,
key: resolution.provider.identifier,
providedKind: resolution.node.kind,
provider: resolution.provider,
});
}
assertIsNode(resolution.node, options.kinds);
}
const resolved = this.resolveWithin(resolution.node, resolution.depth);
return (resolved ?? undefined) as Exclude<GetNodeFromKind<TKind>, InjectedValueNode> | undefined;
}

public clone(): ProvidedScope {
return new ProvidedScope(...this.frames);
}

/** Find the node an injection stands for, searching frames strictly below `depth`. */
private lookup(node: InjectedValueNode, depth: number): Resolution | undefined {
const found = this.find(node.key, depth);
if (found) {
const { depth: providerDepth, provider } = found;
if (!isNode(provider.node, 'injectedValueNode')) {
return { depth: providerDepth, node: provider.node, provider };
}
const chained = this.lookup(provider.node, providerDepth);
if (chained) return { ...chained, provider: chained.provider ?? provider };
}
if (node.fallback === undefined) return undefined;
return isNode(node.fallback, 'injectedValueNode')
? this.lookup(node.fallback, depth)
: { depth, node: node.fallback };
Comment thread
lorisleiva marked this conversation as resolved.
}

/**
* Replace every injection nested within `node`, resolving against frames
* strictly below `depth`. Returns `null` when any of them is unresolvable,
* and `node` itself when it contains none.
*/
private resolveWithin(node: Node, depth: number): Node | null {
let replaced = false;
let unresolvable = false;
const visitor = bottomUpTransformerVisitor([
child => {
if (unresolvable || !isNode(child, 'injectedValueNode')) return child;
replaced = true;
const resolution = this.lookup(child, depth);
const resolved = resolution ? this.resolveWithin(resolution.node, resolution.depth) : null;
if (resolved === null) unresolvable = true;
return resolved;
},
]);
const result = visit(node, visitor);
if (unresolvable) return null;
return replaced ? result : node;
}

/** Search frames strictly below `depth`, innermost first. */
private find(key: IdentifierString, depth: number): { depth: number; provider: ProvidedNode } | undefined {
for (let index = depth - 1; index >= 0; index--) {
const provider = this.frames[index].find(p => p.identifier === key);
if (provider) return { depth: index, provider };
}
return undefined;
}
}
Loading
Loading