### Output of quick start example
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/README.md
The output printed by the quick start example when the graph is valid.
```text
a -> b
b -> c
```
--------------------------------
### Run examples with zig build
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/CUSTOM_PROCESSORS.md
Use the Zig build system to execute the custom processor and composed markup examples.
```bash
zig build examples
```
--------------------------------
### Initialize markup parser buffers
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/MEMORY.md
Example of initializing fixed storage and scratch buffers for the markup parser.
```zig
var nodes: markup.FixedDocumentStorage(.{ .nodes = 16, .attributes = 32 }) = .{};
var frames: markup.FixedParseScratch(8) = .{}; // deepest element nesting
```
--------------------------------
### Build and test commands
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/README.md
Use these commands to verify the project, build examples, check freestanding compilation, and run benchmarks.
```sh
zig build test # all tests
zig build examples # build and run every example
zig build check-freestanding # compile for RISC-V32 and Wasm32
zig build bench -Doptimize=ReleaseFast # main benchmark
```
--------------------------------
### Install dot-parser via Zig CLI
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/README.md
Use the Zig fetch command to add the dot-parser package to your project.
```sh
zig fetch --save git+https://github.com/AshutoshMahala/dot-parser#v0.5.0
```
--------------------------------
### Configure GrowableDiagnosticBag limit
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ERRORS.md
Example of initializing a growable diagnostic bag with a custom entry limit.
```zig
var bag = dot.GrowableDiagnosticBag.init(allocator, .{
.max_entries = .{ .limited = 10_000 }, // up to 65,535; or `.unlimited`
});
```
--------------------------------
### Example DOT graph structure
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/README.md
A sample DOT file content demonstrating nodes, edges, attributes, and subgraphs.
```dot
digraph Pipeline {
node [shape=box];
fetch -> parse -> check [color=red];
subgraph cluster_output { render; save }
check -> { render save }
}
```
--------------------------------
### requestMarkup and processPendingMarkup usage
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EDITORS.md
Example showing how to queue specific labels for markup checking and then process them, using the dot-parser library.
```APIDOC
## requestMarkup and processPendingMarkup
### Description
This example demonstrates how to selectively check markup labels in a DOT document after parsing. It disables automatic markup checking, keeps results, queues specific labels, and then processes them.
### Usage
```zig
const Editor = dot.Profile(.{
.policy = .{ .markup = .passthrough, .retention = .{ .markup = true } },
.processors = .{ .markup = markup.Profile(.{ .policy = .{
.retention = .{ .partial = true },
} }) },
});
var bag = Editor.GrowableDiagnosticBag.init(allocator, .{});
defer bag.deinit();
var result = try Editor.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator);
if (result.dot.document) |document| {
for (document.attributes) |attribute| {
if (std.mem.eql(u8, document.text(attribute.key), "label"))
try result.requestMarkup(allocator, attribute.value);
}
}
// The chosen labels are queued; none has been checked yet.
try Editor.processPendingMarkup(allocator, &result, bag.sink(), .{});
// Read the results with result.markupResults().
```
### Notes
- `requestMarkup` takes one whole value, including its `<...>`. It checks the range and spelling, queues each `<...>` part of a joined value, and ignores other parts.
- Queue values in source order, without overlaps. A repeat or a step backwards returns `error.SelectionOutOfOrder`.
- A bad range or spelling, or running out of memory, leaves the queue as it was.
- Calling `processPendingMarkup` closes the queue. Queueing more, or processing again, returns `error.SelectionClosed`.
- The label checker's run-time settings and cancel check are passed fresh as `.markup` options to `processPendingMarkup`; its resources go in `.markup_resources`.
- If the DOT parse stopped early or failed with fail-fast, this call can't continue past that.
- With `.collect`, label checking can still go ahead even if DOT validation reported `.insufficient_scratch`, as long as every diagnostic was delivered and the bag didn't ask to stop. With `.fail_fast` it can't.
- Checking labels never reruns DOT validation, so `result.dot.documentValid()` and `result.documentValid()` stay `false`.
- Use the same allocator for parsing, queueing, processing and freeing. Keep the source alive and unchanged.
- Diagnostics arrive in order: DOT's first, then the chosen labels in source order.
```
--------------------------------
### PolicySet Preparation
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/CUSTOM_PROCESSORS.md
Prepares settings for several named processors at once using dot.processor.PolicySet. Sets can nest, and each run-time setting is checked once before any work starts.
```APIDOC
## PolicySet Preparation
### Description
Prepares settings for several named processors at once using dot.processor.PolicySet. Sets can nest, and each run-time setting is checked once before any work starts.
### Usage
- Define a PolicySet with named processor policies.
- Call prepare with a patch of run-time settings.
- The result can be used to create Prepared instances for each processor.
### Example
```zig
const Labels = markup.Profile(.{ .runtime_policy = true });
const Group = dot.processor.PolicySet(.{ .parser = Labels, .marker = Marker });
const App = dot.processor.PolicySet(.{ .dot = dot.Profile(.{}), .markup = Group });
const state = try App.prepare(.{ .markup = .{
.parser = .{ .policy = .{ .validation = .{ .duplicate_attribute = .warning } } },
.marker = .{ .policy = .{ .target = '?' } },
} });
const ready: Labels.Prepared = .{ .policies = state.markup.parser };
// Reuse `ready` without preparing again.
```
```
--------------------------------
### Initialize FixedDocumentStorage and FixedDiagnosticBag
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/MEMORY.md
Example of declaring fixed buffers for a document and diagnostic bag to avoid dynamic allocation.
```zig
var storage: dot.FixedDocumentStorage(.{
.statements = 32,
.nodes = 32,
.edges = 16,
}) = .{};
var bag: dot.FixedDiagnosticBag(8) = .{};
const parsed = dot.parseBorrowedIn(source, .{ .document = storage.storage() }, bag.sink(), .{});
if (parsed.outcome == .success) {
const document = parsed.document.?;
const validation = dot.validate(&document, bag.sink(), .{});
_ = validation.documentValid();
}
// Nothing to free. Reuse or drop `storage`.
```
--------------------------------
### Check DOT file via CLI
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ERRORS.md
Command-line usage for the check_file example. Supports --compact for one-line output and --fail-fast to stop at the first error.
```bash
./zig-out/bin/check_file graph.dot
```
--------------------------------
### Example of compact diagnostic output
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ERRORS.md
A sample representation of how a diagnostic appears when rendered using the compact log style.
```text
error[dot_parser:E.Syntax.Grammar.031]: input ended before the document was complete
--> sample.dot:6:1: (byte column, offset 56, len 0)
detail: while parsing the document body: expected a statement or '}', found end of input
note: unclosed delimiter opened at 1:9; misindented closing brace at 5:1
help: the input ends inside this scope; add the missing '}'; the '}' at 5:1 is indented like an outer scope, so the missing brace probably belongs above it
fix: insert '}' at end of input (one possible repair)
```
--------------------------------
### Session.init with cancellation
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EXECUTION.md
Example of initializing a Session with a cancellation check function. The session calls the provided function before every step to determine if work should stop.
```APIDOC
## Session.init with cancellation
### Description
Initializes a parsing session with a cancellation check. The session calls the provided function before every step to determine if work should stop.
### Usage
```zig
const Request = struct {
stop: bool = false,
fn poll(context: ?*anyopaque) bool {
const self: *@This() = @ptrCast(@alignCast(context.?));
return self.stop;
}
};
const Session = dot.Profile(.{ .policy = .{ .execution = .{
.metering = true,
.cancellation = true,
} } }).Session;
var request: Request = .{};
var session = Session.init(source, .{ .document = storage.storage() }, bag.sink(), .{
.cancellation = .{ .context = &request, .is_requested = Request.poll },
});
defer session.deinit();
```
### Parameters
- `source` - The input source to parse.
- `document` - The document storage.
- `sink` - The diagnostic sink.
- `cancellation` - Configuration with `context` and `is_requested` function.
### Notes
- The cancellation check is a plain function call; no threads, signals, or timers are used internally.
- If another thread sets the flag, make it atomic.
```
--------------------------------
### Configure and parse with label retention
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EDITORS.md
Example of setting up the parser profile with retention enabled and iterating over the retained label results.
```APIDOC
## Configure and parse with label retention
### Description
Set up the parser with retention enabled and parse a DOT source, then iterate over the retained label results.
### Configuration
- `dot.Profile` with `.policy.retention.partial = true` and `.policy.retention.markup = true`
- `markup.Profile` with `.policy.retention.partial = true`
### Usage
```zig
const Editor = dot.Profile(.{
.policy = .{ .retention = .{ .partial = true, .markup = true } },
.processors = .{ .markup = markup.Profile(.{ .policy = .{
.retention = .{ .partial = true },
} }) },
});
var bag = Editor.GrowableDiagnosticBag.init(allocator, .{});
defer bag.deinit();
var result = try Editor.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator); // frees the DOT document and every label tree
for (result.markupResults() orelse &.{}) |child| {
_ = child.envelope; // the whole <...> value, in DOT file positions
_ = child.input; // the label's inner bytes and where they start in the file
_ = child.result.parse.document; // the label's tree; may be partial or null
_ = child.result.validation;
}
```
### Notes
- All three retention settings are off by default.
- `markupResults()` returns null when keeping is off.
- Entries are in source order and remain valid even if the DOT parse fails later.
- Do not free entries individually; `result.deinit` frees everything.
```
--------------------------------
### Configure Graphviz validation profile
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/MARKUP.md
This example demonstrates the default settings for a Graphviz markup profile, including error handling for unknown elements and invalid attributes.
```zig
const Labels = markup.Profile(.{ .policy = .{
.mode = .graphviz,
.validation = .{ .graphviz = .{
.unknown_element = .err,
.invalid_attribute = .err,
} },
} });
var result = try Labels.parseAndValidate(allocator, .{
.bytes = "
",
.origin = 0,
}, bag.sink(), .{});
defer result.deinit();
```
--------------------------------
### session.reset(source, sink, options)
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EXECUTION.md
Starts a new parse in the same buffers. Documents from the earlier parse become invalid.
```APIDOC
## session.reset(source, sink, options)
### Description
Starts a new parse in the same buffers. Documents from the earlier parse become invalid.
### Method
reset
### Parameters
- **source** - The source buffer for the new parse.
- **sink** - The sink for the new parse.
- **options** - Options for the new parse.
```
--------------------------------
### Configure FixedParseScratch for nested subgraphs
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/MEMORY.md
Example of providing temporary space for nested subgraphs using FixedParseScratch.
```zig
var pools: dot.FixedDocumentStorage(.{ .statements = 20, .subgraphs = 20 }) = .{};
var scratch: dot.FixedParseScratch(.{ .nesting = 4 }) = .{};
const parsed = dot.parseBorrowedIn(source, .{
.document = pools.storage(),
.scratch = scratch.storage(),
}, bag.sink(), .{});
```
--------------------------------
### Implement a custom diagnostic sink
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ERRORS.md
Example of creating a custom sink structure to count errors and using it within the parseAndValidate operation.
```zig
const Counter = struct {
errors: usize = 0,
fn emit(context: ?*anyopaque, problem: dot.Diagnostic) dot.DiagnosticSinkError!dot.DiagnosticAction {
const self: *Counter = @ptrCast(@alignCast(context.?));
if (problem.code.info().severity == .err) self.errors += 1;
return .proceed;
}
fn sink(self: *Counter) dot.DiagnosticSink {
return .{ .context = self, .emit_fn = emit };
}
};
var counter: Counter = .{};
var result = dot.parseAndValidate(allocator, source, counter.sink(), .{});
defer result.deinit(allocator);
```
--------------------------------
### Validate repeated attributes with scratch memory
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/POLICIES.md
Example of configuring a profile to warn on repeated attributes and allocating the necessary scratch memory for validation.
```zig
const Checks = dot.Profile(.{ .policy = .{ .validation = .{ .repeated_attribute = .warning } } });
const keys = try allocator.alloc(dot.AttributeKeyScratch, dot.requiredValidationScratch(&document));
defer allocator.free(keys);
const checked = Checks.validate(&document, bag.sink(), .{
.scratch = .{ .attribute_keys = keys },
});
```
--------------------------------
### Define an HTML-like label in DOT
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/LABELS.md
Example of using an HTML-like label within a DOT graph definition.
```dot
digraph {
a [label=<Bold and italic>];
}
```
--------------------------------
### Configure validation restrictions in Zig
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/POLICIES.md
Example of setting up a profile that restricts undirected graphs, generic graphs, and subgraphs, reporting errors for violations.
```zig
const Lint = dot.Profile(.{ .policy = .{ .validation = .{
.invalid_encoding = .err,
.restrictions = .{
.graph_kinds = .{ .undigraph = .err, .generic = .err },
.subgraphs = .err,
},
} } });
```
--------------------------------
### Configure Custom Markup Profile
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/MARKUP.md
Example of defining a custom markup profile in Zig with specific error handling and closing tag recovery settings.
```zig
const Custom = markup.Profile(.{ .policy = .{
.mode = .structural,
.on_error = .collect,
.closing_tag_recovery = .two_edits,
} });
```
--------------------------------
### Parser with fail_fast policy
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ERRORS.md
Example of configuring the DOT parser to stop at the first error using the fail_fast policy.
```APIDOC
## Parser with fail_fast policy
### Description
Configure the DOT parser to stop at the first error instead of collecting multiple errors.
### Usage
```zig
const Parser = dot.Profile(.{ .policy = .{ .on_error = .fail_fast } });
var result = Parser.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator);
```
### Parameters
- `allocator` - memory allocator
- `source` - input DOT source
- `bag.sink()` - diagnostic sink
- `{}` - options (empty)
### Notes
- Validation follows the same setting.
- Warnings never trigger fail-fast.
```
--------------------------------
### Parse and traverse a markup fragment in Zig
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/MARKUP.md
Initializes a diagnostic bag and parses a markup string. The example demonstrates how to iterate through document roots, inspect node properties, and access attributes and children.
```zig
const markup = @import("markup_parser");
var bag = markup.GrowableDiagnosticBag.init(allocator, .{});
defer bag.deinit();
var parsed = markup.parseBorrowed(allocator, "Hello world!", bag.sink(), .{});
defer parsed.deinit();
if (parsed.document) |document| {
var nodes = document.roots();
while (nodes.next()) |node| {
_ = node.kind(); // .element, .text, .comment or .cdata
_ = node.name(); // tag name, or null for text
_ = node.raw(); // the exact source text of this node
var attributes = node.attributes();
while (attributes.next()) |attribute| {
_ = attribute.name();
_ = attribute.value(); // without quotes, not decoded
}
var children = node.children();
while (children.next()) |child| _ = child;
}
}
```
--------------------------------
### Example output for digraph { a -- b }
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/GETTING_STARTED.md
Shows the console output when rendering the problem for the invalid graph 'digraph { a -- b }'. The output includes the error code dot_parser:E.Validation.Operator.002 and a suggested fix.
```text
┌─ Error 1: edge operator does not match the graph kind
│ graph.dot:1:13
│
│ 1 │ digraph { a -- b }
│ │ ───┬─── ^^ expected '->', found '--'
│ │ └──── the document is directed because of this keyword
│
│ Hint: change '--' to '->', or declare the document with 'graph'
│ Fix: replace '--' with '->' (one possible repair)
└─ E1 ─ [dot_parser:E.Validation.Operator.002]
```
--------------------------------
### Parse and validate a DOT graph with dot-parser in Zig
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/README.md
Parses a DOT graph from a string, validates it, and prints each edge. Diagnostics are collected in a GrowableDiagnosticBag and rendered if the document is invalid. The example is from examples/quick_start.zig.
```zig
const std = @import("std");
const dot = @import("dot_parser");
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
var buffer: [4096]u8 = undefined;
var stdout_writer: std.Io.File.Writer = .init(.stdout(), init.io, &buffer);
const stdout = &stdout_writer.interface;
defer stdout.flush() catch {};
const source =
\\digraph {
\\ a -> b;
\\ b -> c [color=red];
\\}
;
// Problems are collected here instead of being printed or thrown.
var bag = dot.GrowableDiagnosticBag.init(allocator, .{});
defer bag.deinit();
// Parse the text, then check it (for example, `--` inside a digraph).
var result = dot.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator);
if (!result.documentValid()) {
for (bag.items(), 1..) |problem, number| {
try dot.console.renderBoxed(problem, number, .{ .source = source, .source_name = "graph.dot" }, stdout);
}
return;
}
const document = result.document.?;
var edges = document.edgeIterator();
while (edges.next()) |edge| {
// An edge end is a node or a whole subgraph (`a -> { b c }`).
if (edge.left != .node or edge.right != .node) continue;
const from = document.nodeReference(edge.left.node).?.identifier;
const to = document.nodeReference(edge.right.node).?.identifier;
try stdout.print("{s} {s} {s}\n", .{
document.text(from), edge.operator.lexeme(), document.text(to),
});
}
}
```
--------------------------------
### Iterate over document statements
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/GETTING_STARTED.md
Walks through all statements in the document in source order, handling each of the six kinds: node, edge, edge_chain, subgraph, assignment, and attribute_statement. Uses document.text() to get the exact source bytes for ranges.
```zig
var statements = document.statements();
while (statements.next()) |statement| switch (statement) {
.node => |node| {
const name = document.nodeReference(node.reference).?.identifier;
std.debug.print("node {s}\n", .{document.text(name)});
},
.edge => |edge| std.debug.print("edge using {s}\n", .{edge.operator.lexeme()}),
.edge_chain => |chain| std.debug.print("chain of {d} edges\n", .{document.edgeLinkCount(chain) + 1}),
.subgraph => |id| std.debug.print("subgraph #{d}\n", .{@intFromEnum(id)}),
.assignment => |assignment| std.debug.print("{s} = {s}\n", .{
document.text(assignment.key), document.text(assignment.value),
}),
.attribute_statement => |defaults| std.debug.print("{s} defaults\n", .{@tagName(defaults.target)}),
};
```
--------------------------------
### Prepare settings for multiple processors with PolicySet
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/CUSTOM_PROCESSORS.md
Demonstrates nesting processor configurations and preparing them using dot.processor.PolicySet.
```zig
const Labels = markup.Profile(.{ .runtime_policy = true });
const Group = dot.processor.PolicySet(.{ .parser = Labels, .marker = Marker });
const App = dot.processor.PolicySet(.{ .dot = dot.Profile(.{}), .markup = Group });
const state = try App.prepare(.{ .markup = .{
.parser = .{ .policy = .{ .validation = .{ .duplicate_attribute = .warning } } },
.marker = .{ .policy = .{ .target = '?' } },
} });
const ready: Labels.Prepared = .{ .policies = state.markup.parser };
// Reuse `ready` without preparing again.
```
--------------------------------
### Initialize and execute a BoundedSession
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EXECUTION.md
Initializes a markup session with document and scratch storage, then executes a budget loop using advance until an outcome is reached.
```zig
var session = markup.BoundedSession.init(source, .{
.document = nodes.storage(),
.scratch = frames.storage(),
}, bag.sink(), .{});
defer session.deinit();
while (session.advance(64).outcome == null) {}
```
--------------------------------
### document.scope(id)
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/READING_DOCUMENTS.md
Looks up a scope by its ScopeId. Use document.scope(.root).? to get the whole document scope.
```APIDOC
## document.scope(id)
### Description
Looks up a scope by its ScopeId. Use document.scope(.root).? to get the whole document scope.
### Parameters
- **id** (ScopeId) - Required - The scope identifier.
### Returns
- **?Scope** - Optional - The scope, or null if not found.
### Example
```zig
const scope = document.scope(.root).?;
```
```
--------------------------------
### Basic BoundedSession loop in Zig
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EXECUTION.md
Demonstrates initializing a BoundedSession with fixed storage and diagnostic buffers, then advancing the parser in 64-credit increments until completion.
```zig
var storage: dot.FixedDocumentStorage(.{
.statements = 32, .nodes = 32, .edges = 16, .attributes = 32,
}) = .{};
var bag: dot.FixedDiagnosticBag(4) = .{};
var session = dot.BoundedSession.init(source, .{ .document = storage.storage() }, bag.sink(), .{});
defer session.deinit();
while (true) {
const progress = session.advance(64); // spend at most 64 credits
if (progress.outcome != null) break; // finished
// Not finished yet: go do other work, then come back.
}
const parsed = session.result().?;
if (parsed.outcome == .success) {
const document = parsed.document.?;
_ = document;
}
```
--------------------------------
### Run all benchmarks with Zig build commands
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/PERFORMANCE.md
Run each benchmark individually using zig build with ReleaseFast optimization. The first four commands accept -Dlexer=scalar (and also -Dlexer=block for repeat runs). bench-markup supports -- --scopes-only and -- --graphviz-only flags. check-benches only verifies compilation.
```sh
zig build bench -Doptimize=ReleaseFast -Dlexer=scalar
zig build bench-lexer -Doptimize=ReleaseFast -Dlexer=scalar
zig build bench-session -Doptimize=ReleaseFast -Dlexer=scalar
zig build bench-subgraphs -Doptimize=ReleaseFast -Dlexer=scalar
zig build bench-policy -Doptimize=ReleaseFast
zig build bench-markup -Doptimize=ReleaseFast
zig build bench-markup -Doptimize=ReleaseFast -- --scopes-only
zig build bench-markup -Doptimize=ReleaseFast -- --graphviz-only
zig build bench-composition -Doptimize=ReleaseFast
zig build check-benches # only checks that they compile
```
--------------------------------
### Initialize diagnostic bag and parse DOT source
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ERRORS.md
Demonstrates the standard pattern for parsing and validating DOT source using a GrowableDiagnosticBag to collect issues.
```zig
var bag = dot.GrowableDiagnosticBag.init(allocator, .{});
defer bag.deinit();
var result = dot.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator);
if (result.documentValid()) {
// Use result.document.?
} else {
// Show bag.items() to the user.
}
```
--------------------------------
### Create a custom markup profile
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/MARKUP.md
To override preset settings while maintaining specific limits, copy the preset and modify the mode as shown.
```zig
const Custom = markup.Profile(.{ .policy = blk: {
var policy = markup.presets.untrusted;
policy.mode = .structural;
break :blk policy;
} });
```
--------------------------------
### Configure markup parser for partial retention
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EDITORS.md
Demonstrates initializing the Editor with .partial retention enabled and inspecting the resulting document state, including checking element completion status.
```zig
const Editor = markup.Profile(.{ .policy = .{
.mode = .structural,
.retention = .{ .partial = true },
} });
var parsed = Editor.parseBorrowed(allocator, "; null for text, comments, CDATA
}
_ = document.unrepresented(); // the source the tree doesn't cover
}
```
--------------------------------
### Configure a custom policy with fail_fast
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/POLICIES.md
Demonstrates how to define a custom Parser profile with a specific policy and use it to parse and validate source input.
```zig
const Parser = dot.Profile(.{ .policy = .{ .on_error = .fail_fast } });
var result = Parser.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator);
```
--------------------------------
### Build and Test Commands
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ARCHITECTURE.md
A collection of Zig build commands used for testing, benchmarking, and verifying compilation across different targets.
```sh
zig build test # everything
zig build test-markup # markup only, without building DOT
zig build examples # build and run all examples
zig build check-freestanding # RISC-V32 and Wasm32 compile checks
zig build check-benches # compile benchmarks without running them
zig build -Doptimize=ReleaseFast test --fuzz=1000 # longer fuzzing
```
--------------------------------
### Parser.parseBorrowed with .encoding
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ENCODINGS.md
Example of passing the .encoding option to Parser.parseBorrowed to force a specific encoding. The encoding option overrides any byte order mark.
```APIDOC
## Parser.parseBorrowed
### Description
Parses a source buffer using the specified encoding. The .encoding option forces the reader to use the given encoding, and only its own byte order mark is skipped.
### Method
parseBorrowed
### Parameters
- allocator: Allocator - Required - Memory allocator for parsing.
- source: []const u8 - Required - The source buffer to parse.
- sink: Sink - Required - The sink to receive parsed events.
- options: Options - Required - Parsing options, including .encoding.
### Options
- .encoding: Encoding - Optional - The encoding to use. Choices: .ascii, .utf8, .utf16le, .utf16be, .utf32le, .utf32be.
### Example
```zig
var parsed = try Parser.parseBorrowed(allocator, source, bag.sink(), .{
.encoding = .utf16be,
});
defer parsed.deinit(allocator);
```
### Errors
- error.TruncatedCodeUnit - The file ends partway through a code unit.
- error.UnsupportedEncoding - The file needs a reader that isn't compiled in.
- error.SourceTooLarge - The file is larger than 4 GiB.
- error.Cancelled - Cancellation is on and was already requested (for UTF-16, UTF-32, ASCII).
```
--------------------------------
### Define a custom processor schema with PolicyBinding
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/CUSTOM_PROCESSORS.md
Defines a Schema struct with Policy, Effective, defaults, resolve, and check members, then binds it using dot.processor.PolicyBinding.
```zig
const Schema = struct {
pub const Policy = struct { target: ?u8 = null };
pub const Effective = struct { target: u8 };
pub const defaults: Effective = .{ .target = '!' };
pub const Error = error{};
pub const Check = union(enum) { valid };
pub fn resolve(baseline: Effective, patch: Policy) Effective {
return .{ .target = patch.target orelse baseline.target };
}
pub fn check(_: Effective, _: Policy) Check {
return .valid;
}
};
const Marker = struct {
pub const Policies = dot.processor.PolicyBinding(Schema, .{ .runtime_policy = true });
};
```
--------------------------------
### Render a list of diagnostics using dot.console.renderBoxedList
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ERRORS.md
Use locationCapacity to allocate a scratch array for line number calculation before rendering a list of diagnostics in a boxed format.
```zig
const locations = try allocator.alloc(dot.location.Location,
try dot.console.locationCapacity(bag.items()));
defer allocator.free(locations);
try dot.console.renderBoxedList(bag.items(), 0, .{
.source = source,
.source_name = "graph.dot",
}, locations, writer);
```
--------------------------------
### Example of label validation error output
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/LABELS.md
A sample diagnostic output showing how label validation errors are reported with their specific line and column location in the DOT file.
```text
┌─ Error 1: repeated attribute name on one element
│ example.dot:1:39
│
│ 1 │ digraph { a [label=<Hello |reference| {
const node = document.nodeReference(reference).?;
_ = node.identifier;
},
.subgraph => |id| {
// `a -> { b c }`: the right end is a whole subgraph.
const scope = document.scope(id).?;
_ = scope;
},
}
_ = edge.operator; // .directed (->) or .undirected (--)
_ = edge.attributes; // shared by every edge of a chain
}
```
--------------------------------
### Configure block scanner with dot.Profile
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EXECUTION.md
Use this Zig code to configure the DOT parser to use the .block scanner, which reads 64 bytes at a time using vector instructions. This scanner performs better with very small budgets or files with long names, strings, or comments, but may be slower on targets without vector instructions.
```zig
const Parser = dot.Profile(.{ .policy = .{ .scanner = .block } });
```
--------------------------------
### Configure session cancellation with a poll function
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EXECUTION.md
Demonstrates how to enable execution cancellation by defining a poll function and passing it to the session configuration.
```zig
const Request = struct {
stop: bool = false,
fn poll(context: ?*anyopaque) bool {
const self: *@This() = @ptrCast(@alignCast(context.?));
return self.stop;
}
};
const Session = dot.Profile(.{ .policy = .{ .execution = .{
.metering = true,
.cancellation = true,
} } }).Session;
var request: Request = .{};
var session = Session.init(source, .{ .document = storage.storage() }, bag.sink(), .{
.cancellation = .{ .context = &request, .is_requested = Request.poll },
});
defer session.deinit();
```
--------------------------------
### Wrap the built-in markup parser
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/CUSTOM_PROCESSORS.md
A template for creating a custom processor by wrapping the built-in markup parser, allowing for custom checks during the parse and validate phase.
```zig
const MyLabels = struct {
const Base = markup.Profile(.{});
pub const Policies = Base.Policies;
pub const Options = Base.Options;
pub const Diagnostic = markup.Diagnostic;
pub const DiagnosticSink = markup.DiagnosticSink;
pub const InputError = markup.Fragment.Error;
pub const ParseResources = struct {};
pub const console = markup.console;
pub const Prepared = struct {
inner: Base.Prepared,
pub fn initWorkspace(self: @This(), allocator: std.mem.Allocator, _: ParseResources) Workspace {
return .{ .inner = self.inner.initWorkspace(allocator, .{}) };
}
};
pub const Workspace = struct {
inner: Base.Workspace,
pub fn parseAndValidate(self: *@This(), input: markup.Fragment, sink: DiagnosticSink) InputError!markup.FixedFragmentResult {
// Add your own checks here, reporting rebased spans.
return self.inner.parseAndValidate(input, sink);
}
pub fn deinit(self: *@This()) void {
self.inner.deinit();
}
};
pub fn prepare(options: Options) Prepared {
return .{ .inner = Base.prepare(options) };
}
};
```
--------------------------------
### Parse and validate DOT source
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/GETTING_STARTED.md
Initialize a diagnostic bag, parse the source, and validate the resulting document. The source buffer must remain alive while the document is in use.
```zig
const dot = @import("dot_parser");
var bag = dot.GrowableDiagnosticBag.init(allocator, .{});
defer bag.deinit();
var result = dot.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator);
if (result.documentValid()) {
const document = result.document.?;
// ... read the document ...
}
```
--------------------------------
### Checking many fragments with a workspace
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/MARKUP.md
Demonstrates using a workspace to parse and validate multiple fragments efficiently. The workspace reuses memory across calls, and the result is valid only until the next call or deinit.
```zig
const Labels = markup.Profile(.{ .policy = markup.presets.untrusted });
const ready = Labels.prepare(.{});
var workspace = ready.initWorkspace(allocator, .{}); // allocates nothing yet
defer workspace.deinit();
for (fragments) |fragment| {
const checked = try workspace.parseAndValidate(fragment, bag.sink());
// Use checked.parse.document now. The next call reuses its memory.
if (checked.shouldStop(.collect)) break;
}
```
--------------------------------
### Queue and process specific labels
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EDITORS.md
Configures an Editor with markup retention, parses a source, and queues specific 'label' attributes for later validation using processPendingMarkup.
```zig
const Editor = dot.Profile(.{
.policy = .{ .markup = .passthrough, .retention = .{ .markup = true } },
.processors = .{ .markup = markup.Profile(.{ .policy = .{
.retention = .{ .partial = true },
} }) },
});
var bag = Editor.GrowableDiagnosticBag.init(allocator, .{});
defer bag.deinit();
var result = try Editor.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator);
if (result.dot.document) |document| {
for (document.attributes) |attribute| {
if (std.mem.eql(u8, document.text(attribute.key), "label"))
try result.requestMarkup(allocator, attribute.value);
}
}
// The chosen labels are queued; none has been checked yet.
try Editor.processPendingMarkup(allocator, &result, bag.sink(), .{});
// Read the results with result.markupResults().
```
--------------------------------
### Enable partial DOT file retention with retention.partial
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/EDITORS.md
Configure the editor profile to retain the finished portion of a DOT file by setting retention.partial to true. This allows the parser to return a document even when the source is incomplete or contains errors.
```zig
const Editor = dot.Profile(.{ .policy = .{
.retention = .{ .partial = true },
} });
var result = Editor.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator);
if (result.document) |*document| {
_ = document.state; // .complete or .partial
_ = document.scopeComplete(); // is the DOT itself complete (not: is it valid)
_ = document.unrepresented(); // the source the document doesn't cover, or null
var scopes = document.subgraphs();
while (scopes.next()) |scope| {
_ = scope.state(); // each subgraph is complete or partial too
_ = scope.sourceRange();
}
}
```
--------------------------------
### dot.console.render
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ERRORS.md
Renders a single diagnostic in compact log style.
```APIDOC
## dot.console.render
### Description
Renders one diagnostic in compact log style.
### Method
Function
### Signature
`dot.console.render(diagnostic, options, writer)`
### Parameters
- **diagnostic** (Diagnostic) - Required - The diagnostic to render.
- **options** (RenderOptions) - Required - Rendering options.
- **writer** (Writer) - Required - The output writer.
### Options
Same as `renderBoxed`.
### Example
```zig
try dot.console.render(diagnostic, .{
.source = source,
.source_name = "graph.dot",
}, writer);
```
```
--------------------------------
### Parse with any allocator
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/MEMORY.md
The simplest memory management approach where the result is explicitly deinitialized using the provided allocator.
```zig
var result = dot.parseAndValidate(gpa, source, bag.sink(), .{});
defer result.deinit(gpa);
```
--------------------------------
### Configure source_encodings in dot.Profile
Source: https://github.com/ashutoshmahala/dot-parser/blob/main/docs/ENCODINGS.md
Define supported encodings at compile time within the dot.Profile configuration to enable direct reading of UTF-8, UTF-16, or UTF-32 files.
```zig
const Parser = dot.Profile(.{
.source_encodings = &.{ .utf8, .utf16, .utf32 },
});
var result = try Parser.parseAndValidate(allocator, source, bag.sink(), .{});
defer result.deinit(allocator);
```