Skip to content

About

Examples of PetitParser for Dart.

Topics

Resources

Stars

19 stars

Watchers

1 watching

Forks

Repository files navigation

PetitParser Examples

Pub Package Build Status Code Coverage GitHub Issues GitHub Forks GitHub Stars GitHub License

A collection of real-world grammars, evaluators, interactive tools, and performance benchmarks illustrating PetitParser for Dart.

This package showcases how to model domain-specific notations, standard interchange formats, and full programming languages directly in plain Dart.

Highlights

  • Grammar Catalog: Practical parser definitions ranging from small data formats like JSON, BibTeX (with streaming via package:petitparser/stream.dart and LaTeX decoding), CSV/TSV, and URIs to full programming languages such as Pascal, Python, Smalltalk, and Dart, as well as CommonMark/GFM Markdown (with AST-driven syntax highlighting and HTML rendering).
  • Interpreters and Evaluators: Working interpreters for Prolog with SLD-resolution search and Lisp with lexical scoping and native functions, plus an expression evaluator and WebGL 2D/3D math plotter.
  • Automata Engine: Regular expression parser compiling abstract syntax trees directly into non-deterministic finite automata for pattern matching.
  • Interactive Tools: Ready-to-use console command line REPLs and browser playgrounds, including an XML SAX/DOM and XPath 3.1 explorer.
  • Performance Benchmarks: Microbenchmarks measuring standard parsing, fast non-capturing parsing, and comparisons with native platform parsers.

Installation

Add PetitParser and the examples package to your project dependencies:

dart pub add petitparser petitparser_examples

Grammars

BibTeX

Parses BibTeX files into sealed, strongly typed BibTeXNode objects (BibTeXEntry, BibTeXString, BibTeXPreamble, BibTeXComment), with lazy LaTeX accent/HTML-entity decoding via normalizeFieldValue and lazy/chunked streaming via nodeParser and package:petitparser/stream.dart.

import 'package:petitparser_examples/bibtex.dart';

void main() {
  final parser = BibTeXDefinition().build();
  final result = parser.parse(r'''
@inproceedings{Reng10c,
  title = "Practical Dynamic Grammars for Dynamic Languages",
  author = "Lukas Renggli and Stéphane Ducasse and Tudor Gîrba and Oscar Nierstrasz",
  year = 2010
}''');

  final entry = result.value.whereType<BibTeXEntry>().single;
  print(entry.key);      // Reng10c
  print(entry.type);     // inproceedings
  print(entry['title']); // Practical Dynamic Grammars for Dynamic Languages
}

Try the interactive BibTeX Browser & Search to download, search, filter, and export citations from real-world .bib files directly in the browser.

Dart

A comprehensive implementation of the Dart 3 grammar and parser producing strongly-typed Abstract Syntax Trees (ASTs). Supports records, patterns, switch expressions, class modifiers, enhanced enums, extension types, shorthand new/factory constructors, null-aware collection elements, and null safety.

import 'package:petitparser_examples/dart.dart';

void main() {
  final unit = parseDart('void main() => print("Hello, Dart!");');
  print(unit.declarations.first); // FunctionDeclarationNode(main)
}

Try the interactive Dart Grammar Visualizer to parse Dart code and explore its AST in the browser.

JSON

A complete implementation of the JSON specification. Transforms JSON text into native Dart maps, lists, strings, numbers, booleans, and null values.

import 'package:petitparser_examples/json.dart';

void main() {
  final data = parseJson(
    '{"name": "PetitParser", "tags": ["dart", "parser"], "active": true}',
  );
  print(data); // {name: PetitParser, tags: [dart, parser], active: true}
}

Try the interactive JSON Parser & Benchmark to compare PetitParser's pure-Dart JSON grammar against the platform native parser.

Lisp

A Lisp grammar and tree-walking evaluator supporting symbols, numbers, strings, quoted forms, lexical closures, and native functions.

import 'package:petitparser_examples/lisp.dart';

void main() {
  final environment = NativeEnvironment();
  final result = evalString(lispParser, environment, '(+ 1 (* 2 3))');
  print(result); // 7
}

Run the interactive console REPL:

dart run bin/lisp/lisp.dart

Or try the interactive Lisp Interpreter in the browser.

Markdown

A CommonMark and GitHub Flavored Markdown (GFM) parser producing strongly-typed Abstract Syntax Trees (ASTs), with support for converting documents to HTML and syntax highlighting.

import 'package:petitparser_examples/markdown.dart';

void main() {
  final document = parseMarkdown('# Hello World\n\nThis is **bold** text.');
  print(document.blocks.first); // HeadingNode(level: 1, content: TextNode("Hello World"))

  final html = markdownToHtml('# Hello World\n\nThis is **bold** text.');
  print(html); // <h1>Hello World</h1>\n<p>This is <strong>bold</strong> text.</p>
}

Try the interactive Markdown Parser & Syntax Highlighter for live in-browser preview, syntax highlighting, and HTML rendering.

Math

A mathematical expression evaluator built using ExpressionBuilder. Handles operator precedence, associativity, parentheses, variables, and standard mathematical functions.

import 'package:petitparser_examples/math.dart';

void main() {
  final expression = parser.parse('sqrt(16) + 2 ^ 3').value;
  print(expression.eval({})); // 12.0
}

Try the interactive Math Evaluator or the WebGL 2D & 3D Math Plotter in the browser.

Pascal

A grammar for Pascal following the 1978 Apple Pascal Standard.

import 'package:petitparser/petitparser.dart';
import 'package:petitparser_examples/pascal.dart';

void main() {
  final parser = PascalParserDefinition().build();
  final result = parser.parse('''
program HelloWorld;
begin
  writeln('Hello, World!');
end.
''');
  print(result is Success); // true
}

Try the interactive Pascal Grammar Visualizer to inspect Pascal ASTs in the browser.

Prolog

A Prolog grammar and inference engine supporting facts, rules, unification, and variable substitution.

import 'package:petitparser_examples/prolog.dart';

void main() {
  final db = Database.parse('''
parent(bob, ann).
parent(bob, pat).
sibling(X, Y) :- parent(Z, X), parent(Z, Y).
''');
  final query = Term.parse('sibling(ann, S)');
  for (final solution in db.query(query)) {
    print(solution); // sibling(ann, ann), sibling(ann, pat)
  }
}

Run the interactive console REPL:

dart run bin/prolog/prolog.dart

Or try the interactive Prolog Interpreter in the browser.

Python

A grammar and parser for modern Python 3.12+ source code producing strongly-typed Abstract Syntax Trees (ASTs). Supports match/case pattern matching, PEP 695 type parameter syntax, walrus operator, f-strings, exception groups, async/await, and indentation-based suite parsing.

import 'package:petitparser_examples/python.dart';

void main() {
  final module = parsePython('def add(a: int, b: int) -> int:\n    return a + b\n');
  print(module.body.first); // FunctionDefNode(name: add, args: ..., body: 1)
}

Try the interactive Python AST Visualizer to parse and inspect Python syntax trees in the browser.

Regular Expressions

A parser and compiler for regular expressions. Compiles parsed patterns into non-deterministic finite automata supporting concatenation, alternation, repetition, and character classes.

import 'package:petitparser_examples/regexp.dart';

void main() {
  final nfa = Nfa.fromString(r'a*b+');
  print(nfa.matchAsPrefix('aaab') != null); // true
  print(nfa.matchAsPrefix('b') != null);    // true
  print(nfa.matchAsPrefix('a') != null);    // false
}

Try the interactive RegExp Playground to visualize ASTs, NFA transition tables, and pattern matches in the browser.

Smalltalk

A complete Smalltalk grammar exported from the original PetitParser implementation in Smalltalk, foundational to the Helvetia Language Workbench.

import 'package:petitparser/petitparser.dart';
import 'package:petitparser_examples/smalltalk.dart';

void main() {
  final parser = SmalltalkParserDefinition().build();
  final result = parser.parse('''
example
  1 to: 10 do: [ :i | Transcript show: i printString ]
''');
  print(result is Success); // true
}

Try the interactive Smalltalk Grammar Visualizer to inspect Smalltalk ASTs in the browser.

Tabular (CSV and TSV)

A configurable parser definition for delimited text formats with support for custom delimiters, quotation characters, and escaping rules.

import 'package:petitparser_examples/tabular.dart';

void main() {
  final csv = TabularDefinition.csv().build();
  final result = csv.parse(
    'language,paradigm\nDart,multi-paradigm\nSmalltalk,object-oriented',
  );
  print(result.value);
  // [[language, paradigm], [Dart, multi-paradigm], [Smalltalk, object-oriented]]
}

Try the interactive Tabular Text Parser for CSV and TSV parsing in the browser.

URI

Decomposes RFC-3986 URI strings into structured components including scheme, authority, user info, host, port, path, query parameters, and fragments.

import 'package:petitparser_examples/uri.dart';

void main() {
  final result = uri.parse(
    'https://user:pass@example.com:8080/path/to/page?lang=en#heading',
  );
  print(result.value.scheme);   // https
  print(result.value.hostname); // example.com
  print(result.value.port);     // 8080
  print(result.value.path);     // /path/to/page
}

Try the interactive URI Parser to decompose RFC-3986 URIs in the browser.

XML

The web/xml directory demonstrates parsing XML documents into event streams, constructing DOM trees, pretty printing, and evaluating XPath 3.1 expressions using the xml package.

Try the interactive XML & XPath Explorer in the browser.

Web Applications

Interactive browser playgrounds and visualization tools are located in the web/ directory.

To run the web applications locally:

dart pub global activate webdev
webdev serve --release

Open http://localhost:8080/ to browse the interactive playgrounds for BibTeX search & browsing, Dart grammar visualization, JSON, Lisp, Markdown live rendering & syntax highlighting, Math evaluation, Math plotting, Pascal AST visualization, Prolog, Python AST visualization, Regular Expressions, Smalltalk, Tabular data, URI parsing, and XML.

Benchmarks

Run performance benchmarks directly with the Dart CLI:

dart run --no-enable-asserts bin/benchmark/benchmark.dart

Each suite measures standard parsing throughput, fast non-capturing parse performance, and compares results against native implementations where available.

To run correctness verification without running the performance suite:

dart run bin/benchmark/benchmark.dart --no-benchmark

Resources

About

Examples of PetitParser for Dart.

Topics

Resources

Stars

19 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages