0
# Parser Creation
1
2
Core functionality for creating parsers from grammar definitions. Supports both JSON and Bison-style grammar formats with automatic algorithm selection.
3
4
## Capabilities
5
6
### Parser Constructor
7
8
Creates a parser from a grammar definition with optional configuration.
9
10
```javascript { .api }
11
/**
12
* Create a parser from a grammar definition
13
* @param grammar - Grammar definition (object or string)
14
* @param options - Parser generation options
15
* @returns Parser instance ready for parsing
16
*/
17
function Parser(grammar, options);
18
```
19
20
The Parser constructor accepts:
21
- **grammar**: Either a JavaScript object containing the grammar definition, or a string in Bison format
22
- **options**: Optional configuration object for parser generation
23
24
**Usage Examples:**
25
26
```javascript
27
const jison = require("jison");
28
const Parser = jison.Parser;
29
30
// Simple calculator grammar
31
const calculatorGrammar = {
32
"lex": {
33
"rules": [
34
["\\s+", "/* skip whitespace */"],
35
["[0-9]+", "return 'NUMBER';"],
36
["\\+", "return '+';"],
37
["\\-", "return '-';"],
38
["\\*", "return '*';"],
39
["\\/", "return '/';"],
40
["\\(", "return '(';"],
41
["\\)", "return ')';"],
42
["$", "return 'EOF';"]
43
]
44
},
45
"bnf": {
46
"expressions": [["e EOF", "return $1;"]],
47
"e": [
48
["e + e", "$$ = $1 + $3;"],
49
["e - e", "$$ = $1 - $3;"],
50
["e * e", "$$ = $1 * $3;"],
51
["e / e", "$$ = $1 / $3;"],
52
["( e )", "$$ = $2;"],
53
["NUMBER", "$$ = Number(yytext);"]
54
]
55
}
56
};
57
58
const parser = new Parser(calculatorGrammar);
59
```
60
61
### Generator Factory
62
63
Factory function for creating parser generators with specific algorithms.
64
65
```javascript { .api }
66
/**
67
* Factory function for creating parser generators
68
* @param grammar - Grammar definition
69
* @param options - Generation options including parser type
70
* @returns Appropriate generator instance based on options.type
71
*/
72
function Generator(grammar, options);
73
```
74
75
The Generator function returns different generator classes based on the `options.type`:
76
- `'lr0'` - Returns LR0Generator
77
- `'slr'` - Returns SLRGenerator
78
- `'lalr'` - Returns LALRGenerator (default)
79
- `'lr'` - Returns LR1Generator
80
- `'ll'` - Returns LLGenerator
81
82
**Usage Examples:**
83
84
```javascript
85
const jison = require("jison");
86
87
// Create LALR(1) generator (default)
88
const generator = new jison.Generator(grammar);
89
90
// Create specific algorithm generator
91
const lr1Generator = new jison.Generator(grammar, { type: 'lr' });
92
const llGenerator = new jison.Generator(grammar, { type: 'll' });
93
94
// Generate parser
95
const parser = generator.createParser();
96
```
97
98
### Direct Algorithm Constructors
99
100
Direct constructors for specific parsing algorithms.
101
102
```javascript { .api }
103
/**
104
* LR(0) parser generator constructor
105
* @param grammar - Grammar definition
106
* @param options - Generation options
107
*/
108
function LR0Generator(grammar, options);
109
110
/**
111
* SLR(1) parser generator constructor
112
* @param grammar - Grammar definition
113
* @param options - Generation options
114
*/
115
function SLRGenerator(grammar, options);
116
117
/**
118
* LALR(1) parser generator constructor
119
* @param grammar - Grammar definition
120
* @param options - Generation options
121
*/
122
function LALRGenerator(grammar, options);
123
124
/**
125
* Canonical LR(1) parser generator constructor
126
* @param grammar - Grammar definition
127
* @param options - Generation options
128
*/
129
function LR1Generator(grammar, options);
130
131
/**
132
* LL(1) parser generator constructor
133
* @param grammar - Grammar definition
134
* @param options - Generation options
135
*/
136
function LLGenerator(grammar, options);
137
```
138
139
**Usage Examples:**
140
141
```javascript
142
const jison = require("jison");
143
const { LALRGenerator, LR1Generator } = jison;
144
145
// Direct construction
146
const lalrGen = new LALRGenerator(grammar, { debug: true });
147
const lr1Gen = new LR1Generator(grammar);
148
149
// Create parsers
150
const lalrParser = lalrGen.createParser();
151
const lr1Parser = lr1Gen.createParser();
152
```
153
154
### Parser Instance Methods
155
156
Methods available on generated parser instances.
157
158
```javascript { .api }
159
/**
160
* Parse input string and return result
161
* @param input - String to parse
162
* @returns Parse result or throws error on failure
163
*/
164
parse(input);
165
166
/**
167
* Generate parser source code
168
* @param options - Code generation options
169
* @returns Generated parser source as string
170
*/
171
generate(options);
172
173
/**
174
* Generate CommonJS module source
175
* @param options - Module generation options
176
* @returns CommonJS module source code
177
*/
178
generateCommonJSModule(options);
179
180
/**
181
* Generate AMD module source
182
* @param options - AMD generation options
183
* @returns AMD module source code
184
*/
185
generateAMDModule(options);
186
```
187
188
**Usage Examples:**
189
190
```javascript
191
const parser = new Parser(grammar);
192
193
// Parse input
194
try {
195
const result = parser.parse("2 + 3 * 4");
196
console.log(result); // 14
197
} catch (error) {
198
console.error("Parse error:", error.message);
199
}
200
201
// Generate standalone parser
202
const parserSource = parser.generate({
203
moduleName: "MyParser",
204
moduleType: "commonjs"
205
});
206
207
// Write to file
208
require('fs').writeFileSync('my-parser.js', parserSource);
209
```
210
211
## Grammar Format Support
212
213
### JSON Grammar Format
214
215
Structured JavaScript object format for defining grammars.
216
217
```javascript
218
const jsonGrammar = {
219
"lex": {
220
"rules": [
221
["pattern", "action"],
222
// ... more rules
223
]
224
},
225
"bnf": {
226
"nonterminal": [
227
["production rule", "semantic action"],
228
// ... more productions
229
]
230
},
231
"operators": [
232
["associativity", "operator1", "operator2"],
233
// ... more operator declarations
234
]
235
};
236
```
237
238
### Bison-Style Grammar Format
239
240
String format compatible with Bison grammar files.
241
242
```javascript
243
const bisonGrammar = `
244
%lex
245
%%
246
\\s+ /* skip whitespace */
247
[0-9]+ return 'NUMBER'
248
"+" return '+'
249
%%
250
251
%left '+'
252
%left '*'
253
254
%%
255
expressions: e EOF { return $1; };
256
e: e '+' e { $$ = $1 + $3; }
257
| NUMBER { $$ = Number(yytext); }
258
;
259
`;
260
261
const parser = new Parser(bisonGrammar);
262
```
263
264
## Error Handling
265
266
Parser creation can throw errors for invalid grammars or unsupported configurations.
267
268
```javascript
269
try {
270
const parser = new Parser(invalidGrammar);
271
} catch (error) {
272
if (error.message.includes('Grammar error')) {
273
console.error('Invalid grammar:', error.message);
274
} else {
275
console.error('Parser creation failed:', error.message);
276
}
277
}
278
```
279
280
Common error conditions:
281
- Missing or empty grammar definition
282
- Invalid BNF/EBNF syntax
283
- Conflicting operator precedence
284
- Unsupported parser algorithm type
285
- Grammar conflicts that cannot be resolved