Dart용 PetitParser 프레임워크의 기능을 보여주는 예제 파서, 애플리케이션 및 벤치마크 모음입니다. 텍스트 처리, 언어 분석, 데이터 추출을 위한 사용자 정의 파서를 구축하고 사용하는 방법을 설명합니다. 실제 시나리오에서 PetitParser의 강력한 파싱 조합자를 이해하고 적용하는 데 도움을 주기 위해 설계되었습니다. 간단한 문법 검증부터 복잡한 문법 구현에 이르기까지 다양한 용도를 다룹니다. Flutter 및 기타 Dart 환경에서 파싱 로직을 학습하고 테스트하기에 적합합니다.
사용 사례
파서 생성 학습
구문 분석 로직 테스트
도메인 전용 언어 구축
구조화된 텍스트 입력 검증
구성 파일 파서 구현
사용자 지정 구문 강조 기능 만들기
주요 기능
포괄적인 예제 세트
현실 세계의 파싱 시나리오
벤치마킹 도구
크로스 플랫폼 호환성
Dart 프로젝트와의 간편한 통합
잘 문서화된 코드 샘플
적합한 대상
파싱에 처음 도전하는 Dart 개발자
교육 목적
프로토타입 언어 프로세서
파서 동작 디버깅
Flutter 앱에서 DSL 만들기
고려 사항
PetitParser의 기본 사항을 이해해야 합니다
독립형 파서 라이브러리가 아님
petitparser 패키지와 함께 사용하는 것이 가장 좋습니다
완전한 기능을 위해 추가 설정이 필요할 수 있습니다
예시는 설명용이며, 생산 준비가 되지 않았습니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
PetitParser Examples
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, CSV, and URIs to full programming languages such as Pascal, Smalltalk, and Dart.
Interpreters and Evaluators: Working interpreters for Prolog with resolution search and Lisp with lexical scoping and native functions.
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 applications.
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 strongly typed entry objects with citation keys and key-value fields.
import'package:petitparser_examples/bibtex.dart';
voidmain() {
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.single;
print(entry.key); // Reng10cprint(entry.type); // inproceedingsprint(entry.fields); // {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, and null safety.
import'package:petitparser_examples/dart.dart';
voidmain() {
final unit = parseDart('void main() => print("Hello, Dart!");');
print(unit.declarations.first); // FunctionDeclarationNode(main)
}
JSON
A complete implementation of the JSON specification. Transforms JSON text into native Dart maps, lists, strings, numbers, booleans, and null values.
A Lisp grammar and tree-walking evaluator supporting symbols, numbers, strings, quoted forms, lexical closures, and native functions.
import'package:petitparser_examples/lisp.dart';
voidmain() {
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
Math
A mathematical expression evaluator built using ExpressionBuilder. Handles operator precedence, associativity, parentheses, variables, and standard mathematical functions.
A grammar for Pascal following the 1978 Apple Pascal Standard.
import'package:petitparser_examples/pascal.dart';
voidmain() {
final parser = PascalParserDefinition().build();
final result = parser.parse('''
program HelloWorld;
begin
writeln('Hello, World!');
end.
''');
print(result isSuccess); // true
}
Prolog
A Prolog grammar and inference engine supporting facts, rules, unification, and variable substitution.
import'package:petitparser_examples/prolog.dart';
voidmain() {
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
Regular Expressions
A parser and compiler for regular expressions. Compiles parsed patterns into non-deterministic finite automata supporting concatenation, alternation, repetition, and character classes.
A complete Smalltalk grammar exported from the original PetitParser implementation in Smalltalk, foundational to the Helvetia Language Workbench.
import'package:petitparser_examples/smalltalk.dart';
voidmain() {
final parser = SmalltalkParserDefinition().build();
final result = parser.parse('''
example
1 to: 10 do: [ :i | Transcript show: i printString ]
''');
print(result isSuccess); // true
}
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';
voidmain() {
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]]
}
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';
voidmain() {
final result = uri.parse(
'https://user:pass@example.com:8080/path/to/page?lang=en#heading',
);
print(result.value.scheme); // httpsprint(result.value.hostname); // example.comprint(result.value.port); // 8080print(result.value.path); // /path/to/page
}
XML
The web/xml directory demonstrates parsing XML documents into event streams, constructing DOM trees, pretty printing, and evaluating XPath expressions using the xml package.
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, Math evaluation, Math plotting, Prolog, 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