Skip to content

API reference

Everything below is exported from the package root unless noted. The large example grammars live behind a separate subpath so they tree-shake away when unused:

import { Engine, rule, importGrammar } from "graph-grammar";
import { EXAMPLES, buildExample } from "graph-grammar/examples";

Drives a grammar over a host graph.

const engine = new Engine(grammar, start?);
MemberSignatureDescription
constructor(grammar: Grammar, start?: Graph)Clones the start graph (the axiom is never mutated).
graphget (): GraphThe current host graph.
stepsnumberRewrite steps taken so far.
step(): RewriteResultApply one rewrite; returns what changed.
run(maxSteps?, onStep?): numberRun to completion (or a bound); returns steps taken.
reset(start?: Graph): voidReset to the axiom (or a new start graph).
matchCounts(cap?): Record<string, number>Per-rule match counts, for UI badges.

A RewriteResult reports applied, ruleId, and the createdNodes, createdEdges, deletedNodes, deletedEdges id arrays.

ExportSignatureDescription
findMatches(ruleId, lhs, index): Match[]All matches of a pattern in the indexed host.
findOneMatch(ruleId, lhs, index, rng?): Match | nullA single (optionally random) match.
hasMatch(lhs, index): booleanWhether any match exists.
countMatches(lhs, index, cap?): numberCount matches (optionally capped).
evalPredicate(pred, value): booleanEvaluate a single property predicate.
ExportDescription
GraphIndexMutable indexed view of a graph (adjacency, label buckets, incident-edge sets) used by the matcher and rewriter.
makeNode(label, props?, x?, y?)Create a GNode with a fresh id.
makeEdge(source, target, label?, directed?, props?)Create a GEdge with a fresh id.
emptyGraph(){ nodes: [], edges: [] }.
cloneGraph(g)Deep clone a graph.
graphStats(g)Node/edge counts and label histogram.
ExportSignatureDescription
applyRule(index, rule, match, ctx): ApplyResultApply a matched rule to the index in place.

Types: RewriteContext, ApplyResult.

Concise constructors that keep the verbose data model out of hand-written grammars.

ExportSignature
pn(id, label, opts?) → PatternNode
pe(id, source, target, opts?) → PatternEdge
rn(id, label, opts?) → RhsNode (opts.mapFrom to preserve)
re(id, source, target, opts?) → RhsEdge
emb(lhsNodeId, strategy, opts?) → EmbeddingRule
rule(spec: RuleSpec) → Rule (derives the morphism from mapFrom)
defaultEmbedding(lhs, rhs) → EmbeddingRule[]
grammar(name, rules, start, config?) → Grammar

Property-expression helpers: lit(value), randInt(min, max), counter(), copyProp(from, key), incProp(from, key, by?).

ExportDescription
exportGrammar(g) / exportGraph(g)Serialize to pretty JSON.
importGrammar(text)Parse + validate a grammar; throws on invalid input.
safeImportGrammar(text)Non-throwing: { ok, grammar } | { ok: false, error }.
parseGraph(text)Parse a graph from JSON, edge-list, or DOT-lite.
randomGraph(n, edgeFactor, labels)Generate a random graph.
gridGraph(cols, rows, label?)Generate a grid graph.

See Serialization & validation.

Every type has a matching schema, kept in lockstep with the TypeScript types at compile time:

PropValueSchema, PropsSchema, GNodeSchema, GEdgeSchema, GraphSchema, PredicateOpSchema, PropPredicateSchema, PatternNodeSchema, PatternEdgeSchema, PatternGraphSchema, PropExprSchema, RhsNodeSchema, RhsEdgeSchema, RhsGraphSchema, EmbeddingStrategySchema, EmbeddingRuleSchema, MorphismSchema, RuleSchema, ApplicationStrategySchema, GrammarConfigSchema, GrammarSchema.

ExportDescription
uid(prefix?)Generate a unique id.
resetCounter()Reset the id counter (deterministic tests).
RNGSeeded PRNG (mulberry32).
deepClone(value)Structured deep clone.
clamp(x, min, max)Clamp a number.

All data-model types are exported: Graph, GNode, GEdge, Props, PropValue, PatternGraph, PatternNode, PatternEdge, RhsGraph, RhsNode, RhsEdge, PropExpr, PropPredicate, PredicateOp, EmbeddingRule, EmbeddingStrategy, Rule, Morphism, RuleSpec, Grammar, GrammarConfig, ApplicationStrategy, Match, RewriteResult.

ExportDescription
EXAMPLESArray of { key, title, blurb, build } example entries.
buildExample(key)Build a ready-to-run Grammar by key (e.g. "triangle", "plant", "dungeon").
ExampleEntryThe entry type.

Built by Kiberon Labs