@argtype/core
v0.1.0
Published
Reference parser for argtype, a type language for command-line argument grammars. Lexes and parses argtype source into an AST; consumer-neutral (no code generation, no validation policy).
Maintainers
Readme
@argtype/core
The reference parser for argtype, a type language for command-line argument grammars. Full language docs and spec: nx10.dev/argtype.
npm install @argtype/coreUsage
Four steps; only the first is required.
import { parseArgtype, inlineAliases, resolveAnnotations, printArgtype } from "@argtype/core";
const parsed = parseArgtype(source); // source -> AST
if (!parsed.ok) throw new Error("no usable tree");
const inlined = inlineAliases(parsed.doc); // substitute alias references
const resolved = resolveAnnotations(inlined.doc); // typed core decorations
const text = printArgtype(parsed.doc); // AST -> sourceparseArgtype returns { ok, doc, diagnostics }. ok is false only when there
is no usable tree at all - the parser recovers from most errors, so a document
can be ok and still carry diagnostics.
The parser interprets nothing
It keeps set as set, keeps every any branch, leaves alias references
unresolved, treats frontmatter as opaque, and preserves sugar ((a, b) does not
become seq(a, b), = 3 does not become .default(3)). Comments and
blank-line grouping are kept on the AST, so parse -> print is a faithful
formatter.
Most importantly, there is no list of known method names in the parser. Every
.method(...) is recorded verbatim, so an extension this package has never heard
of survives to a consumer that implements it.
Extensions are imports, not flags
resolveAnnotations handles the spec core (naming, docs, .default(),
.min()/.max(), .join(), .count*()) and checks each decoration landed on a
node that can carry it. Everything else is a separate opt-in pass returning
results keyed by node, with its own diagnostics and target rules:
const { outputs } = resolveOutputs(resolved.doc);
outputs.get(node); // ResolvedOutput[] | undefined| Extension | Function | Vocabulary |
| ------------- | -------------------- | --------------------------------- |
| outputs | resolveOutputs | .output() + path templates |
| mediatypes | resolveMediaTypes | .mediaType() on path |
| paths | resolvePaths | .mutable() / .resolveParent() |
| constraints | resolveConstraints | .requires() / .conflicts() |
Never importing paths means never enforcing its rules. Every annotation stays
on the resolved node in annotations (a Map by method name), so a third-party
extension is as well supported as these four - and CORE_METHODS plus each
*_METHODS set let you report whatever nothing in your pipeline claimed.
Writing one uses the same pieces the shipped four use, all exported:
import { Diagnostics, asString, isTerminal, visitResolved } from "@argtype/core";
export function resolveRetries(doc) {
const d = new Diagnostics();
const retries = new Map();
visitResolved(doc, (node) => {
const anns = node.annotations.get("retries");
if (!anns) return;
if (node.kind !== "ref" && !isTerminal(node, "int")) {
d.err("`.retries()` is only supported on int", "bad-target", node.headSpan);
}
retries.set(node, asString(anns[anns.length - 1].args[0]));
});
return { retries, diagnostics: d.diagnostics };
}Diagnostics are one list
Every pass - parseArgtype, inlineAliases, resolveAnnotations,
resolveReferences, each extension - returns a single diagnostics array whose
entries carry severity, code and a span. Merging results is concatenation,
and partitionDiagnostics(diagnostics) splits them when you want the two
groups.
For editors
Everything is locatable (spans carry 1-based line/column and a 0-based
offset), nothing is dropped, and diagnostics carry a code and severity.
nodeAt(doc, offset); // innermost node under the cursor
annotationAt(doc, offset); // annotations are not nodes, so they need their own lookup
const table = resolveReferences(doc); // non-destructive: the tree keeps its refs
referenceAt(table, offset)?.alias?.nameSpan; // go-to-definition
referencesTo(table, "outfile"); // find-references / rename
visitDocument(doc, (node) => {
if (node.kind === "ref") return "stop"; // `false` skips children, `"stop"` ends the walk
});Use resolveReferences rather than inlineAliases: inlining substitutes
definitions and discards the reference an editor needs to jump from.
Building an AST
build.* constructs nodes without spans, for code generators and codemods.
isSynthetic(span) tells a built node from a parsed one.
const root = build.seq(
build.labelled(build.terminal("path"), "input"),
build.annotated(build.terminal("int"), build.annotation("min", build.number(1))),
);
printArgtype({ aliases: [], rootName: "tool", root });API
| Export | Purpose |
| ------------------------------------------------------------------------------ | ------------------------------------------------- |
| parseArgtype(source) | Source → { ok, doc, diagnostics } |
| inlineAliases(doc) | Substitute alias references, detecting cycles |
| resolveAnnotations(doc) | Typed core decorations, diagnostics, byAst |
| resolveOutputs / resolveMediaTypes / resolvePaths / resolveConstraints | One opt-in extension each |
| CORE_METHODS / OUTPUT_METHODS / … | The names each vocabulary owns |
| Diagnostics / asString / asNumber / isComb / isTerminal | For writing an extension of your own |
| partitionDiagnostics(diagnostics) | Split one list into { errors, warnings } |
| makeError / makeWarning | Construct a Diagnostic |
| SYNTHETIC_SPAN / isSynthetic(span) | The span a built node carries, and its test |
| printArgtype(doc, opts?) | AST → source (round-trips) |
| nodeAt / nodePathAt / annotationAt | What is under a cursor |
| visitDocument / visitNode / visitResolved | Walk the tree |
| spanContains(span, off) | Whether an offset falls in a span (end inclusive) |
| resolveReferences(doc) | Symbol table + go-to-definition |
| build.* | Constructors for synthesizing an AST |
| lexArgtype(source) | Tokens only, for editor tooling |
| splitFrontmatter(source) / toRecord(entries) | The --- block, raw and as plain data |
| parseTemplate(body, pos) | Parse a template literal into tokens |
| splitDocText(raw) | Split a /// block into title and description |
License
MIT
