Skip to content
Back to search

dart-petitparser

Build fast, composable, and type-safe grammars and parsers in Dart.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/petitparser/dart-petitparser with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/petitparser/dart-petitparser'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/petitparser--dart-petitparser/badge.svg)](/listings/petitparser--dart-petitparser)

HTML

<a href="/listings/petitparser--dart-petitparser"><img src="/api/listings/petitparser--dart-petitparser/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Add PetitParser to your Dart or Flutter project:

dart pub add petitparser

Import the package, assemble your parser, and parse key-value pairs:

import 'package:petitparser/petitparser.dart';

void main() {
  // 1. Match a key of one or more letters:
  final key = letter().plus().flatten();

  // 2. Match a numeric value and convert it directly into an integer:
  final value = digit().plus().flatten().map(int.parse);

  // 3. Combine them: match key, discard '=', and match value:
  final entry = key.trim().skip(after: char('=')).then(value.trim());

  // 4. Transform the parsed pair into a typed Dart record:
  final parser = entry.map2((k, v) => (key: k, value: v));

  // 5. Parse the input:
  final result = parser.parse('port = 8080');

  print(result.value); // (key: port, value: 8080)
}

Notice what happened here:

- `letter().plus()` matched consecutive letters, and `.flatten()` turned them into a `String`. - `digit().plus()` matched consecutive digits, and `.map(int.parse)` transformed them immediately into an `int`. - `.skip(after: char('='))` consumed the separator without cluttering the result. - `.then(...)` combined both parts into a strongly typed record `(String, int)`. - `.map2(...)` mapped both positional values into a readable named record.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 515 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # PetitParser for Dart
  2. [![Pub Package](https://img.shields.io/pub/v/petitparser.svg)](https://pub.dev/packages/petitparser)
  3. [![Build Status](https://github.com/petitparser/dart-petitparser/actions/workflows/dart.yml/badge.svg?branch=main)](https://github.com/petitparser/dart-petitparser/actions)
  4. [![Code Coverage](https://codecov.io/gh/petitparser/dart-petitparser/branch/main/graph/badge.svg?token=2yW74MVgun)](https://codecov.io/gh/petitparser/dart-petitparser)
  5. [![GitHub Issues](https://img.shields.io/github/issues/petitparser/dart-petitparser.svg)](https://github.com/petitparser/dart-petitparser/issues)
  6. [![GitHub Forks](https://img.shields.io/github/forks/petitparser/dart-petitparser.svg)](https://github.com/petitparser/dart-petitparser/network)
  7. [![GitHub Stars](https://img.shields.io/github/stars/petitparser/dart-petitparser.svg)](https://github.com/petitparser/dart-petitparser/stargazers)
  8. [![GitHub License](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/petitparser/dart-petitparser/main/LICENSE)
  9. PetitParser makes writing parsers in Dart fast, enjoyable, and fully type-safe.
  10. Instead of writing fragile regular expressions or configuring complex external code generators, PetitParser lets you build parsers directly in plain Dart code. You assemble small, specialized parsers like LEGO bricks to model everything from simple configuration values to full programming languages.
  11. ## ✨ Why PetitParser?
  12. - 🧩 **Composable**: Combine simple parsers into rich grammars using familiar operators and methods.
  13. - 🛡️ **Type-Safe**: Take advantage of modern Dart records, generics, and pattern matching without casting dynamic types.
  14. - ⚡ **Fast & Efficient**: Optimized character predicates and dedicated fast-path parsing keep execution blazing fast.
  15. - 🔍 **Debuggable**: Step through parsing in your IDE, inspect tokens, and visualize execution trees with built-in tools.
  16. - 🛠️ **Extensible**: Transform raw text directly into strongly typed models, syntax trees, or domain objects on the fly.
  17. - 🌐 **Open Source & Battle-Tested**: Highly tested, well-documented, and trusted across production Dart and Flutter applications.
  18. ## 🚀 Quick Start
  19. Add PetitParser to your Dart or Flutter project:
  20. ```bash
  21. dart pub add petitparser
  22. ```
  23. Import the package, assemble your parser, and parse key-value pairs:
  24. ```dart
  25. import 'package:petitparser/petitparser.dart';
  26. void main() {
  27. // 1. Match a key of one or more letters:
  28. final key = letter().plus().flatten();
  29. // 2. Match a numeric value and convert it directly into an integer:
  30. final value = digit().plus().flatten().map(int.parse);
  31. // 3. Combine them: match key, discard '=', and match value:
  32. final entry = key.trim().skip(after: char('=')).then(value.trim());
  33. // 4. Transform the parsed pair into a typed Dart record:
  34. final parser = entry.map2((k, v) => (key: k, value: v));
  35. // 5. Parse the input:
  36. final result = parser.parse('port = 8080');
  37. print(result.value); // (key: port, value: 8080)
  38. }
  39. ```
  40. Notice what happened here:
  41. - `letter().plus()` matched consecutive letters, and `.flatten()` turned them into a `String`.
  42. - `digit().plus()` matched consecutive digits, and `.map(int.parse)` transformed them immediately into an `int`.
  43. - `.skip(after: char('='))` consumed the separator without cluttering the result.
  44. - `.then(...)` combined both parts into a strongly typed record `(String, int)`.
  45. - `.map2(...)` mapped both positional values into a readable named record.
  46. ## 🧩 Core Building Blocks
  47. Every grammar in PetitParser is constructed from three fundamental concepts: matching text, combining parsers, and transforming results.
  48. ### 🔡 Matching Text
  49. Primitive parsers recognize basic character patterns:
  50. - `char('a')` matches an exact single character:
  51. ```dart
  52. char('a').parse('a').value; // 'a'
  53. ```
  54. - `string('dart')` matches an entire string:
  55. ```dart
  56. string('dart').parse('dart').value; // 'dart'
  57. ```
  58. - `digit()` matches any digit from 0 to 9:
  59. ```dart
  60. digit().parse('7').value; // '7'
  61. ```
  62. - `letter()` matches any uppercase or lowercase letter:
  63. ```dart
  64. letter().parse('x').value; // 'x'
  65. ```
  66. - `word()` matches a letter, digit, or underscore:
  67. ```dart
  68. word().parse('_').value; // '_'
  69. ```
  70. - `whitespace()` matches spaces, tabs, and newlines:
  71. ```dart
  72. whitespace().parse(' ').value; // ' '
  73. ```
  74. - `pattern('0-9a-fA-F')` matches any character within a range:
  75. ```dart
  76. pattern('0-9a-fA-F').parse('f').value; // 'f'
  77. ```
  78. - `any()` matches any character:
  79. ```dart
  80. any().parse('!').value; // '!'
  81. ```
  82. Most character parsers accept optional parameters such as `ignoreCase: true` for case-insensitive matching and `unicode: true` for full Unicode code-point support.
  83. ### 🔗 Combining Parsers
  84. Snap individual parsers together to recognize structured input:
  85. - **Sequences**: Run parsers in order. `letter().then(digit())` returns a typed Dart record with each result:
  86. ```dart
  87. letter().then(digit()).parse('a1').value; // ('a', '1')
  88. ```
  89. - **Choices**: Try options in order until one succeeds. `[letter(), digit()].toChoiceParser()` matches either a letter or a digit:
  90. ```dart
  91. [letter(), digit()].toChoiceParser().parse('a').value; // 'a'
  92. ```
  93. - **Repetition**: Repeat patterns to collect multiple matches into a `List`:
  94. - `letter().star()` matches zero or more times:
  95. ```dart
  96. letter().star().parse('abc').value; // ['a', 'b', 'c']
  97. ```
  98. - `digit().plus()` matches one or more times:
  99. ```dart
  100. digit().plus().parse('123').value; // ['1', '2', '3']
  101. ```
  102. - `char('-').optional()` matches zero or one time, returning null when absent:
  103. ```dart
  104. char('-').optional().parse('-').value; // '-'
  105. char('-').optional().parse('+').value; // null
  106. ```
  107. - `letter().times(3)` matches an exact number of occurrences:
  108. ```dart
  109. letter().times(3).parse('abc').value; // ['a', 'b', 'c']
  110. ```
  111. - `digit().plusSeparated(char(','))` matches items separated by a delimiter:
  112. ```dart
  113. digit().plusSeparated(char(',')).parse('1,2,3').value.elements; // ['1', '2', '3']
  114. ```
  115. ### 🎨 Transforming Results
  116. Rather than traversing an untyped syntax tree after the fact, PetitParser lets you transform data while parsing:
  117. - `parser.flatten()` merges matched characters into a single `String`:
  118. ```dart
  119. digit().plus().flatten().parse('123').value; // '123'
  120. ```
  121. - `parser.trim()` discards leading and trailing whitespace around a match:
  122. ```dart
  123. string('true').trim().parse(' true ').value; // 'true'
  124. ```
  125. - `parser.map(callback)` transforms the parsed value with a custom function:
  126. ```dart
  127. digit().plus().flatten().map(int.parse).parse('42').value; // 42
  128. ```
  129. - `parser.map2(callback)` unpacks a two-element record and passes each value as an argument:
  130. ```dart
  131. letter().then(digit()).map2((l, d) => '$l:$d').parse('x9').value; // 'x:9'
  132. ```
  133. - `parser.map3(callback)` similarly unpacks a three-element record:
  134. ```dart
  135. (letter(), char(':'), digit())
  136. .toSequenceParser()
  137. .map3((l, sep, d) => '$l$sep$d')
  138. .parse('a:1')
  139. .value; // 'a:1'
  140. ```
  141. ## 🎯 Handling Results
  142. Calling `parse` on a string returns a `Result`. You can inspect the outcome using Dart pattern matching:
  143. ```dart
  144. final parser = digit().plus().flatten().map(int.parse);
  145. void handleResult(Result<int> result) {
  146. switch (result) {
  147. case Success(value: final value):
  148. print('Parsed $value');
  149. case Failure(message: final message, position: final position):
  150. print('Error at $position: $message');
  151. }
  152. }
  153. handleResult(parser.parse('123')); // Parsed 123
  154. handleResult(parser.parse('abc')); // Error at 0: digit expected
  155. ```
  156. If you only need to know whether an input string conforms to your grammar, use `accept`:
  157. ```dart
  158. if (parser.accept('123')) {
  159. print('Valid input');
  160. }
  161. ```
  162. To extract all matching occurrences across a larger body of text, use `allMatches`:
  163. ```dart
  164. final words = letter().plus().flatten();
  165. final matches = words.allMatches('two words 123');
  166. print(matches); // (two, words)
  167. ```
  168. ## 🛠️ Practical Examples
  169. ### 📋 Delimited Lists
  170. This example parses a comma-separated list of integers like `'1, 2, 3'` into a Dart `List<int>`:
  171. ```dart
  172. final number = digit().plus().flatten().map(int.parse);
  173. final numbers = number
  174. .plusSeparated(char(',').trim())
  175. .map((list) => list.elements);
  176. final result = numbers.parse('1, 2, 3');
  177. print(result.value); // [1, 2, 3]
  178. ```
  179. `list.elements` gives you a typed `List<int>` containing only the parsed numbers, neatly dropping the comma characters.
  180. ### 🧮 Expression Builder
  181. This example parses and evaluates mathematical expressions containing numbers, parentheses, negation, exponentiation, multiplication, division, addition, and subtraction:
  182. ```dart
  183. import 'dart:math' as math;
  184. import 'package:petitparser/petitparser.dart';
  185. final builder = ExpressionBuilder<num>();
  186. // Define primitives like floating-point or integer numbers:
  187. builder.primitive(
  188. digit()
  189. .plus()
  190. .then(char('.').then(digit().plus()).optional())
  191. .flatten()
  192. .trim()
  193. .map(num.parse),
  194. );
  195. // Add parentheses with highest priority:
  196. builder.group().wrapper(
  197. char('(').trim(),
  198. char(')').trim(),
  199. (left, value, right) => value,
  200. );
  201. // Add right-associative power operator:
  202. builder.group().right(
  203. char('^').trim(),
  204. (left, op, right) => math.pow(left, right),
  205. );
  206. // Add prefix operators:
  207. builder.group().prefix(char('-').trim(), (op, value) => -value);
  208. // Add left-associative multiplication and division:
  209. builder.group()
  210. ..left(char('*').trim(), (left, op, right) => left * right)
  211. ..left(char('/').trim(), (left, op, right) => left / right);
  212. // Add left-associative addition and subtraction:
  213. builder.group()
  214. ..left(char('+').trim(), (left, op, right) => left + right)
  215. ..left(char('-').trim(), (left, op, right) => left - right);
  216. final parser = builder.build().end();
  217. print(parser.parse('1 + 2 * 3').value); // 7
  218. print(parser.parse('(1 + 2) * 3').value); // 9
  219. print(parser.parse('2 ^ 2 ^ 3').value); // 256
  220. print(parser.parse('-2 ^ 2').value); // -4
  221. print(parser.parse('-8 + 2').value); // -6
  222. ```
  223. ### 🌲 Recursive Structures
  224. This example parses nested JSON-style arrays of numbers like `'[1, [2, 3], 4]'` into a hierarchy of Dart lists:
  225. ```dart
  226. final value = undefined<Object>();
  227. // An array contains zero or more values separated by commas:
  228. final array = char('[')
  229. .trim()
  230. .then(value.starSeparated(char(',').trim()))
  231. .then(char(']').trim())
  232. .map3((open, elements, close) => elements.elements);
  233. final number = digit().plus().flatten().map(int.parse);
  234. // Wire the recursive definition into the placeholder:
  235. value.set([number, array].toChoiceParser());
  236. final parser = value.end();
  237. print(parser.parse('[1, [2, 3], 4]').value); // [1, [2, 3], 4]
  238. ```
  239. ### 🏛️ Large Grammars
  240. When a grammar grows to dozens or hundreds of productions, organizing rules as separate variables can become difficult to maintain. Subclassing `GrammarDefinition` lets you organize rules as methods on a class, resolving complex mutual recursions cleanly.
  241. This example parses and evaluates arithmetic expressions using a modular, strongly typed grammar definition:
  242. ```dart
  243. class ExpressionGrammarDefinition extends GrammarDefinition<num> {
  244. @override
  245. Parser<num> start() => ref0(term).end();
  246. Parser<num> term() => [ref0(add), ref0(prod)].toChoiceParser();
  247. Parser<num> add() => ref0(prod)
  248. .then(char('+').trim())
  249. .then(ref0(term))
  250. .map3((left, _, right) => left + right);
  251. Parser<num> prod() => [ref0(mul), ref0(prim)].toChoiceParser();
  252. Parser<num> mul() => ref0(prim)
  253. .then(char('*').trim())
  254. .then(ref0(prod))
  255. .map3((left, _, right) => left * right);
  256. Parser<num> prim() => [ref0(parens), ref0(number)].toChoiceParser();
  257. Parser<num> parens() => char('(')
  258. .trim()
  259. .then(ref0(term))
  260. .then(char(')').trim())
  261. .map3((_, value, _) => value);
  262. Parser<num> number() => digit().plus().flatten().trim().map(num.parse);
  263. }
  264. ```
  265. References between rules use `ref0(rule)` to preserve strong types and resolve mutual dependencies dynamically when building the parser:
  266. ```dart
  267. final definition = ExpressionGrammarDefinition();
  268. final parser = definition.build();
  269. print(parser.parse('1 + 2 * 3').value); // 7
  270. print(parser.parse('(1 + 2) * 3').value); // 9
  271. ```
  272. You can also build a parser starting from any specific production rule in the grammar using `buildFrom`:
  273. ```dart
  274. final numberParser = definition.buildFrom(ref0(definition.number));
  275. print(numberParser.parse('42').value); // 42
  276. ```
  277. Organizing grammars this way makes them easy to navigate, refactor, and test production by production in your IDE.
  278. ## 🔬 Advanced Capabilities
  279. ### 📍 Source Positions and Tokens
  280. If you are writing a compiler, linter, or syntax highlighter, you often need to know exactly where in the source file an element appeared. Wrap any parser with `.token()` to capture its start and stop offsets, line number, and column number:
  281. ```dart
  282. final id = letter().plus().flatten().token();
  283. final token = id.parse('hello').value;
  284. print(token.value); // 'hello'
  285. print(token.start); // 0
  286. print(token.stop); // 5
  287. print(token.line); // 1
  288. print(token.column); // 1
  289. ```
  290. ### 🔭 Lookaheads and Semantic Guards
  291. You can inspect the upcoming input stream without consuming characters:
  292. - `parser.and()` performs positive lookahead, succeeding only if `parser` matches next without advancing the input position.
  293. - `parser.not()` performs negative lookahead, succeeding only if `parser` fails to match next.
  294. - `parser.where(predicate)` rejects a match dynamically if a condition is not met.
  295. For example, match a keyword like `let` only when it is not immediately followed by more word characters:
  296. ```dart
  297. final keyword = string('let').skip(after: word().not());
  298. print(keyword.parse('let').value); // 'let'
  299. print(keyword.accept('letter')); // false
  300. ```
  301. ### ⏳ Lazy Repetition
  302. Standard repetition combinators like `star()` are possessive and consume as much input as possible. When matching delimited content like multi-line comments or quoted strings, use `starLazy` or `plusLazy` to stop as soon as a boundary parser succeeds:
  303. ```dart
  304. final comment = string('/*')
  305. .then(any().starLazy(string('*/')).flatten())
  306. .then(string('*/'))
  307. .map3((start, body, end) => body);
  308. print(comment.parse('/* note */').value); // ' note '
  309. ```
  310. ### 📏 Indentation-Based Grammars
  311. Languages like Python or YAML use indentation rather than braces to define code blocks. The `package:petitparser/indent.dart` library provides `Indent` to coordinate indentation levels across nested structures:
  312. - `indent.same`: Matches and consumes the currently active indentation level.
  313. - `indent.during(body)`: Increases indentation before running `body`, verifies deeper indentation, and restores the parent indentation level afterwards (with automatic rollback if `body` fails).
  314. ### 🌊 Streaming and Iteration
  315. For incremental, lazy, and chunked processing across streams or large text inputs, import `package:petitparser/stream.dart`:
  316. - `parser.parseIterable(input)`: Lazily yields parsed tokens from a string as an `Iterable`.
  317. - `parser.parseStream(input)`: Emits parsed results as an asynchronous `Stream`.
  318. - `parser.parseStreamChunks(stream)`: Transforms a chunked `Stream<String>` (e.g. from network sockets or files) into parsed elements, carrying partial tokens across chunk boundaries.
  319. - `parser.toConverter()`: Produces a standard Dart `Converter<String, List<R>>` for chunked stream pipelines.
  320. Candidate selection can be accelerated with `delimiter:` to skip irrelevant input rapidly and recover from false alarms.
  321. ### 🩺 Grammar Linter
  322. Grammars can contain subtle issues such as unreachable branches, infinite loops, or accidental left-recursions. PetitParser provides a built-in linter in `package:petitparser/reflection.dart` that you can run in your tests:
  323. ```dart
  324. import 'package:petitparser/reflection.dart';
  325. import 'package:test/test.dart';
  326. test('grammar verification', () {
  327. final parser = letter().plus();
  328. expect(linter(parser), isEmpty);
  329. });
  330. ```
  331. ### ⏱️ Debugging, Tracing, and Profiling
  332. When a parser behaves unexpectedly on a particular input, wrap it with `trace` to see each step it takes:
  333. ```dart
  334. final parser = letter().then(digit());
  335. trace(parser).parse('a1');
  336. ```
  337. This prints a clear activation tree showing which parsers were called and how they succeeded or failed:
  338. ```text
  339. SequenceParser2<String, String>
  340. SingleCharacterParser[letter expected]
  341. Success<String>[1:2]: a
  342. SingleCharacterParser[digit expected]
  343. Success<String>[1:3]: 1
  344. Success<(String, String)>[1:3]: (a, 1)
  345. ```
  346. For performance tuning, import `package:petitparser/debug.dart` and use `profile(parser)` to measure invocation counts and execution time per parser, or `progress(parser)` to inspect backtracking behavior.
  347. ## 📚 Resources
  348. - [Website](https://petitparser.github.io/): Interactive web demos and ports to other languages.
  349. - [GitHub Repository](https://github.com/petitparser/dart-petitparser): Source code, discussions, and issue tracker.
  350. - [API Documentation](https://pub.dev/documentation/petitparser/latest/): Detailed class and method reference.
  351. - [Examples Repository](https://github.com/petitparser/dart-petitparser-examples): Full implementations for JSON, Lisp, Math, Smalltalk, and more.
  352. ## 📜 History
  353. Grammars for programming languages are traditionally specified statically. They are hard to compose and reuse due to ambiguities that inevitably arise. PetitParser combines ideas from [scannerless parsing](https://en.wikipedia.org/wiki/Scannerless_parsing), [parser combinators](https://en.wikipedia.org/wiki/Parser_combinator), [parsing expression grammars](https://en.wikipedia.org/wiki/Parsing_expression_grammar) (PEG), and packrat parsers to model grammars and parsers as objects that can be reconfigured dynamically.
  354. PetitParser was originally created in [Smalltalk](https://www.lukas-renggli.ch/smalltalk/helvetia/petitparser). Later on, as a way to learn and explore these platforms, I reimplemented PetitParser in [Java](https://github.com/petitparser/java-petitparser) and [Dart](https://github.com/petitparser/dart-petitparser). All implementations share a consistent architecture while adopting the idioms and modern best practices of each target language.
  355. ## 📄 License
  356. The MIT License, see [LICENSE](https://raw.githubusercontent.com/petitparser/dart-petitparser/main/LICENSE).

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.