0
# Peggy
1
2
Peggy is a simple parser generator for JavaScript that produces fast parsers with excellent error reporting. You can use it to process complex data or computer languages and build transformers, interpreters, compilers and other tools easily. Peggy uses parsing expression grammar (PEG) formalism, which is more powerful than traditional LL(k) and LR(k) parsers, integrating both lexical and syntactical analysis in a single step.
3
4
## Package Information
5
6
- **Package Name**: peggy
7
- **Package Type**: npm
8
- **Language**: JavaScript with TypeScript support
9
- **Installation**: `npm install peggy`
10
- **Source Maps**: `npm install source-map-generator` (optional, for source map functionality)
11
12
## Core Imports
13
14
```typescript
15
import { generate, VERSION, RESERVED_WORDS, GrammarError, GrammarLocation, parser, compiler } from "peggy";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const { generate, VERSION, RESERVED_WORDS, GrammarError, GrammarLocation, parser, compiler } = require("peggy");
22
```
23
24
For source map functionality:
25
26
```typescript
27
import { SourceNode } from "source-map-generator";
28
```
29
30
For AST types and visitor system:
31
32
```typescript
33
import type { ast } from "peggy";
34
```
35
36
## Basic Usage
37
38
```typescript
39
import { generate } from "peggy";
40
41
// Define a simple arithmetic grammar
42
const grammar = `
43
Expression
44
= Term (("+" / "-") Term)*
45
46
Term
47
= Factor (("*" / "/") Factor)*
48
49
Factor
50
= "(" Expression ")"
51
/ Number
52
53
Number
54
= [0-9]+
55
`;
56
57
// Generate a parser from the grammar
58
const parser = generate(grammar);
59
60
// Use the generated parser
61
try {
62
const result = parser.parse("2 + 3 * 4");
63
console.log(result); // Parse result
64
} catch (error) {
65
console.error("Parse error:", error.message);
66
}
67
```
68
69
## Architecture
70
71
Peggy is built around several key components:
72
73
- **Grammar Parser**: Parses PEG grammar definitions into Abstract Syntax Trees (AST)
74
- **Compiler Passes**: Multi-stage compilation system that transforms and validates ASTs
75
- **Code Generator**: Produces JavaScript parser code from processed ASTs
76
- **Error Reporting**: Comprehensive error handling with location information
77
- **Type System**: Full TypeScript integration with detailed type definitions
78
- **CLI Tools**: Command-line interface for parser generation and testing
79
80
## Capabilities
81
82
### Parser Generation
83
84
Core functionality for generating parsers from PEG grammars. The main entry point for all parser generation operations.
85
86
```typescript { .api }
87
function generate(grammar: GrammarInput, options?: ParserBuildOptions): Parser;
88
function generate(grammar: GrammarInput, options: SourceBuildOptions<"source">): string;
89
function generate(grammar: GrammarInput, options: SourceBuildOptions<"source-and-map">): SourceNode;
90
function generate(grammar: GrammarInput, options: SourceBuildOptions<"source-with-inline-map">): string;
91
function generate(grammar: GrammarInput, options: SourceOptionsBase<"ast">): ast.Grammar;
92
93
type GrammarInput = SourceText[] | string;
94
95
interface SourceText {
96
source: any;
97
text: string;
98
}
99
```
100
101
[Parser Generation](./parser-generation.md)
102
103
### Grammar Parsing
104
105
Low-level grammar parsing functionality for converting PEG grammar strings into Abstract Syntax Trees.
106
107
```typescript { .api }
108
namespace parser {
109
function parse(grammar: string, options?: Options): ast.Grammar;
110
111
interface Options {
112
grammarSource?: any;
113
reservedWords: string[];
114
startRule?: "Grammar";
115
}
116
}
117
```
118
119
[Grammar Parsing](./grammar-parsing.md)
120
121
### AST Compilation
122
123
Advanced compilation system with multiple passes for transforming, validating, and optimizing grammar ASTs.
124
125
```typescript { .api }
126
namespace compiler {
127
function compile(ast: ast.Grammar, stages: Stages, options?: ParserBuildOptions): Parser;
128
129
interface Stages {
130
prepare: Pass[];
131
check: Pass[];
132
transform: Pass[];
133
generate: Pass[];
134
}
135
}
136
```
137
138
[AST Compilation](./ast-compilation.md)
139
140
### Generated Parser Interface
141
142
Interface and capabilities of parsers generated by Peggy, including parsing options and error handling.
143
144
```typescript { .api }
145
interface Parser {
146
StartRules: string[];
147
SyntaxError: typeof parser.SyntaxError;
148
parse(input: string, options?: ParserOptions): any;
149
}
150
151
interface ParserOptions {
152
grammarSource?: any;
153
startRule?: string;
154
tracer?: ParserTracer;
155
}
156
```
157
158
[Generated Parsers](./generated-parsers.md)
159
160
### Command Line Interface
161
162
Command-line tools for generating parsers, testing grammars, and working with Peggy from the terminal.
163
164
```typescript { .api }
165
class PeggyCLI {
166
parseAsync(): Promise<PeggyCLI>;
167
main(): Promise<number>;
168
}
169
```
170
171
[Command Line Interface](./cli.md)
172
173
## Core Types
174
175
```typescript { .api }
176
/** Current Peggy version in semver format */
177
const VERSION: string;
178
179
/** Default list of reserved words. Contains list of JavaScript reserved words */
180
const RESERVED_WORDS: string[];
181
182
/** Thrown if the grammar contains a semantic error */
183
class GrammarError extends SyntaxError {
184
location?: LocationRange;
185
diagnostics: DiagnosticNote[];
186
stage: Stage | null;
187
problems: Problem[];
188
189
format(sources: SourceText[]): string;
190
}
191
192
/** Location tracking for grammars in larger files */
193
class GrammarLocation {
194
source: any;
195
start: Location;
196
197
constructor(source: unknown, start: Location);
198
static offsetStart(range: LocationRange): Location;
199
static offsetEnd(range: LocationRange): Location;
200
offset(loc: Location): Location;
201
}
202
203
/** Position information */
204
interface Location {
205
line: number;
206
column: number;
207
offset: number;
208
}
209
210
/** Range information */
211
interface LocationRange {
212
source: any;
213
start: Location;
214
end: Location;
215
}
216
217
/** Source text entry for error formatting */
218
interface SourceText {
219
source: any;
220
text: string;
221
}
222
223
/** Grammar input type */
224
type GrammarInput = SourceText[] | string;
225
```
226
227
## Build Options
228
229
```typescript { .api }
230
interface ParserBuildOptions extends BuildOptionsBase {
231
output?: "parser";
232
}
233
234
interface SourceBuildOptions<Output extends SourceOutputs = "source"> extends BuildOptionsBase {
235
output: Output;
236
format?: "amd" | "bare" | "commonjs" | "es" | "globals" | "umd";
237
dependencies?: Dependencies;
238
exportVar?: string;
239
}
240
241
interface BuildOptionsBase {
242
allowedStartRules?: string[];
243
cache?: boolean;
244
grammarSource?: any;
245
plugins?: Plugin[];
246
trace?: boolean;
247
error?: DiagnosticCallback;
248
warning?: DiagnosticCallback;
249
info?: DiagnosticCallback;
250
reservedWords?: string[];
251
}
252
253
/** Parser dependencies mapping */
254
interface Dependencies {
255
[variable: string]: string;
256
}
257
258
/** Plugin interface */
259
interface Plugin {
260
use(config: Config, options: ParserBuildOptions): void;
261
}
262
263
/** Plugin configuration */
264
interface Config {
265
parser: Parser;
266
passes: Stages;
267
reservedWords: string[];
268
}
269
```