UNPKG

15.9 kBTypeScriptView Raw
1/*!
2 * Copyright 2016 The ANTLR Project. All rights reserved.
3 * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
4 */
5import { ANTLRErrorStrategy } from "./ANTLRErrorStrategy";
6import { ATN } from "./atn/ATN";
7import { ErrorNode } from "./tree/ErrorNode";
8import { IntegerStack } from "./misc/IntegerStack";
9import { IntervalSet } from "./misc/IntervalSet";
10import { Lexer } from "./Lexer";
11import { ParseInfo } from "./atn/ParseInfo";
12import { ParserATNSimulator } from "./atn/ParserATNSimulator";
13import { ParserErrorListener } from "./ParserErrorListener";
14import { ParserRuleContext } from "./ParserRuleContext";
15import { ParseTreeListener } from "./tree/ParseTreeListener";
16import { ParseTreePattern } from "./tree/pattern/ParseTreePattern";
17import { RecognitionException } from "./RecognitionException";
18import { Recognizer } from "./Recognizer";
19import { RuleContext } from "./RuleContext";
20import { TerminalNode } from "./tree/TerminalNode";
21import { Token } from "./Token";
22import { TokenFactory } from "./TokenFactory";
23import { TokenStream } from "./TokenStream";
24/** This is all the parsing support code essentially; most of it is error recovery stuff. */
25export declare abstract class Parser extends Recognizer<Token, ParserATNSimulator> {
26 /**
27 * This field maps from the serialized ATN string to the deserialized {@link ATN} with
28 * bypass alternatives.
29 *
30 * @see ATNDeserializationOptions.isGenerateRuleBypassTransitions
31 */
32 private static readonly bypassAltsAtnCache;
33 /**
34 * The error handling strategy for the parser. The default value is a new
35 * instance of {@link DefaultErrorStrategy}.
36 *
37 * @see #getErrorHandler
38 * @see #setErrorHandler
39 */
40 protected _errHandler: ANTLRErrorStrategy;
41 /**
42 * The input stream.
43 *
44 * @see #getInputStream
45 * @see #setInputStream
46 */
47 protected _input: TokenStream;
48 protected readonly _precedenceStack: IntegerStack;
49 /**
50 * The {@link ParserRuleContext} object for the currently executing rule.
51 *
52 * This is always non-undefined during the parsing process.
53 */
54 protected _ctx: ParserRuleContext;
55 /**
56 * Specifies whether or not the parser should construct a parse tree during
57 * the parsing process. The default value is `true`.
58 *
59 * @see `buildParseTree`
60 */
61 private _buildParseTrees;
62 /**
63 * When {@link #setTrace}`(true)` is called, a reference to the
64 * {@link TraceListener} is stored here so it can be easily removed in a
65 * later call to {@link #setTrace}`(false)`. The listener itself is
66 * implemented as a parser listener so this field is not directly used by
67 * other parser methods.
68 */
69 private _tracer;
70 /**
71 * The list of {@link ParseTreeListener} listeners registered to receive
72 * events during the parse.
73 *
74 * @see #addParseListener
75 */
76 protected _parseListeners: ParseTreeListener[];
77 /**
78 * The number of syntax errors reported during parsing. This value is
79 * incremented each time {@link #notifyErrorListeners} is called.
80 */
81 protected _syntaxErrors: number;
82 /** Indicates parser has match()ed EOF token. See {@link #exitRule()}. */
83 protected matchedEOF: boolean;
84 constructor(input: TokenStream);
85 /** reset the parser's state */
86 reset(): void;
87 reset(resetInput: boolean): void;
88 /**
89 * Match current input symbol against `ttype`. If the symbol type
90 * matches, {@link ANTLRErrorStrategy#reportMatch} and {@link #consume} are
91 * called to complete the match process.
92 *
93 * If the symbol type does not match,
94 * {@link ANTLRErrorStrategy#recoverInline} is called on the current error
95 * strategy to attempt recovery. If {@link #getBuildParseTree} is
96 * `true` and the token index of the symbol returned by
97 * {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to
98 * the parse tree by calling {@link #createErrorNode(ParserRuleContext, Token)} then
99 * {@link ParserRuleContext#addErrorNode(ErrorNode)}.
100 *
101 * @param ttype the token type to match
102 * @returns the matched symbol
103 * @ if the current input symbol did not match
104 * `ttype` and the error strategy could not recover from the
105 * mismatched symbol
106 */
107 match(ttype: number): Token;
108 /**
109 * Match current input symbol as a wildcard. If the symbol type matches
110 * (i.e. has a value greater than 0), {@link ANTLRErrorStrategy#reportMatch}
111 * and {@link #consume} are called to complete the match process.
112 *
113 * If the symbol type does not match,
114 * {@link ANTLRErrorStrategy#recoverInline} is called on the current error
115 * strategy to attempt recovery. If {@link #getBuildParseTree} is
116 * `true` and the token index of the symbol returned by
117 * {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to
118 * the parse tree by calling {@link Parser#createErrorNode(ParserRuleContext, Token)} then
119 * {@link ParserRuleContext#addErrorNode(ErrorNode)}.
120 *
121 * @returns the matched symbol
122 * @ if the current input symbol did not match
123 * a wildcard and the error strategy could not recover from the mismatched
124 * symbol
125 */
126 matchWildcard(): Token;
127 /**
128 * Track the {@link ParserRuleContext} objects during the parse and hook
129 * them up using the {@link ParserRuleContext#children} list so that it
130 * forms a parse tree. The {@link ParserRuleContext} returned from the start
131 * rule represents the root of the parse tree.
132 *
133 * Note that if we are not building parse trees, rule contexts only point
134 * upwards. When a rule exits, it returns the context but that gets garbage
135 * collected if nobody holds a reference. It points upwards but nobody
136 * points at it.
137 *
138 * When we build parse trees, we are adding all of these contexts to
139 * {@link ParserRuleContext#children} list. Contexts are then not candidates
140 * for garbage collection.
141 */
142 set buildParseTree(buildParseTrees: boolean);
143 /**
144 * Gets whether or not a complete parse tree will be constructed while
145 * parsing. This property is `true` for a newly constructed parser.
146 *
147 * @returns `true` if a complete parse tree will be constructed while
148 * parsing, otherwise `false`
149 */
150 get buildParseTree(): boolean;
151 getParseListeners(): ParseTreeListener[];
152 /**
153 * Registers `listener` to receive events during the parsing process.
154 *
155 * To support output-preserving grammar transformations (including but not
156 * limited to left-recursion removal, automated left-factoring, and
157 * optimized code generation), calls to listener methods during the parse
158 * may differ substantially from calls made by
159 * {@link ParseTreeWalker#DEFAULT} used after the parse is complete. In
160 * particular, rule entry and exit events may occur in a different order
161 * during the parse than after the parser. In addition, calls to certain
162 * rule entry methods may be omitted.
163 *
164 * With the following specific exceptions, calls to listener events are
165 * *deterministic*, i.e. for identical input the calls to listener
166 * methods will be the same.
167 *
168 * * Alterations to the grammar used to generate code may change the
169 * behavior of the listener calls.
170 * * Alterations to the command line options passed to ANTLR 4 when
171 * generating the parser may change the behavior of the listener calls.
172 * * Changing the version of the ANTLR Tool used to generate the parser
173 * may change the behavior of the listener calls.
174 *
175 * @param listener the listener to add
176 *
177 * @throws {@link TypeError} if `listener` is `undefined`
178 */
179 addParseListener(listener: ParseTreeListener): void;
180 /**
181 * Remove `listener` from the list of parse listeners.
182 *
183 * If `listener` is `undefined` or has not been added as a parse
184 * listener, this method does nothing.
185 *
186 * @see #addParseListener
187 *
188 * @param listener the listener to remove
189 */
190 removeParseListener(listener: ParseTreeListener): void;
191 /**
192 * Remove all parse listeners.
193 *
194 * @see #addParseListener
195 */
196 removeParseListeners(): void;
197 /**
198 * Notify any parse listeners of an enter rule event.
199 *
200 * @see #addParseListener
201 */
202 protected triggerEnterRuleEvent(): void;
203 /**
204 * Notify any parse listeners of an exit rule event.
205 *
206 * @see #addParseListener
207 */
208 protected triggerExitRuleEvent(): void;
209 /**
210 * Gets the number of syntax errors reported during parsing. This value is
211 * incremented each time {@link #notifyErrorListeners} is called.
212 *
213 * @see #notifyErrorListeners
214 */
215 get numberOfSyntaxErrors(): number;
216 get tokenFactory(): TokenFactory;
217 /**
218 * The ATN with bypass alternatives is expensive to create so we create it
219 * lazily.
220 *
221 * @ if the current parser does not
222 * implement the `serializedATN` property.
223 */
224 getATNWithBypassAlts(): ATN;
225 /**
226 * The preferred method of getting a tree pattern. For example, here's a
227 * sample use:
228 *
229 * ```
230 * let t: ParseTree = parser.expr();
231 * let p: ParseTreePattern = await parser.compileParseTreePattern("<ID>+0", MyParser.RULE_expr);
232 * let m: ParseTreeMatch = p.match(t);
233 * let id: string = m.get("ID");
234 * ```
235 */
236 compileParseTreePattern(pattern: string, patternRuleIndex: number): Promise<ParseTreePattern>;
237 /**
238 * The same as {@link #compileParseTreePattern(String, int)} but specify a
239 * {@link Lexer} rather than trying to deduce it from this parser.
240 */
241 compileParseTreePattern(pattern: string, patternRuleIndex: number, lexer?: Lexer): Promise<ParseTreePattern>;
242 get errorHandler(): ANTLRErrorStrategy;
243 set errorHandler(handler: ANTLRErrorStrategy);
244 get inputStream(): TokenStream;
245 /** Set the token stream and reset the parser. */
246 set inputStream(input: TokenStream);
247 /** Match needs to return the current input symbol, which gets put
248 * into the label for the associated token ref; e.g., x=ID.
249 */
250 get currentToken(): Token;
251 notifyErrorListeners(/*@NotNull*/ msg: string): void;
252 notifyErrorListeners(/*@NotNull*/ msg: string, /*@NotNull*/ offendingToken: Token | null, e: RecognitionException | undefined): void;
253 /**
254 * Consume and return the [current symbol](`currentToken`).
255 *
256 * E.g., given the following input with `A` being the current
257 * lookahead symbol, this function moves the cursor to `B` and returns
258 * `A`.
259 *
260 * ```
261 * A B
262 * ^
263 * ```
264 *
265 * If the parser is not in error recovery mode, the consumed symbol is added
266 * to the parse tree using {@link ParserRuleContext#addChild(TerminalNode)}, and
267 * {@link ParseTreeListener#visitTerminal} is called on any parse listeners.
268 * If the parser *is* in error recovery mode, the consumed symbol is
269 * added to the parse tree using {@link #createErrorNode(ParserRuleContext, Token)} then
270 * {@link ParserRuleContext#addErrorNode(ErrorNode)} and
271 * {@link ParseTreeListener#visitErrorNode} is called on any parse
272 * listeners.
273 */
274 consume(): Token;
275 /**
276 * How to create a token leaf node associated with a parent.
277 * Typically, the terminal node to create is not a function of the parent.
278 *
279 * @since 4.7
280 */
281 createTerminalNode(parent: ParserRuleContext, t: Token): TerminalNode;
282 /**
283 * How to create an error node, given a token, associated with a parent.
284 * Typically, the error node to create is not a function of the parent.
285 *
286 * @since 4.7
287 */
288 createErrorNode(parent: ParserRuleContext, t: Token): ErrorNode;
289 protected addContextToParseTree(): void;
290 /**
291 * Always called by generated parsers upon entry to a rule. Access field
292 * {@link #_ctx} get the current context.
293 */
294 enterRule(localctx: ParserRuleContext, state: number, ruleIndex: number): void;
295 enterLeftFactoredRule(localctx: ParserRuleContext, state: number, ruleIndex: number): void;
296 exitRule(): void;
297 enterOuterAlt(localctx: ParserRuleContext, altNum: number): void;
298 /**
299 * Get the precedence level for the top-most precedence rule.
300 *
301 * @returns The precedence level for the top-most precedence rule, or -1 if
302 * the parser context is not nested within a precedence rule.
303 */
304 get precedence(): number;
305 enterRecursionRule(localctx: ParserRuleContext, state: number, ruleIndex: number, precedence: number): void;
306 /** Like {@link #enterRule} but for recursive rules.
307 * Make the current context the child of the incoming localctx.
308 */
309 pushNewRecursionContext(localctx: ParserRuleContext, state: number, ruleIndex: number): void;
310 unrollRecursionContexts(_parentctx: ParserRuleContext): void;
311 getInvokingContext(ruleIndex: number): ParserRuleContext | undefined;
312 get context(): ParserRuleContext;
313 set context(ctx: ParserRuleContext);
314 precpred(localctx: RuleContext, precedence: number): boolean;
315 getErrorListenerDispatch(): ParserErrorListener;
316 inContext(context: string): boolean;
317 /**
318 * Checks whether or not `symbol` can follow the current state in the
319 * ATN. The behavior of this method is equivalent to the following, but is
320 * implemented such that the complete context-sensitive follow set does not
321 * need to be explicitly constructed.
322 *
323 * ```
324 * return getExpectedTokens().contains(symbol);
325 * ```
326 *
327 * @param symbol the symbol type to check
328 * @returns `true` if `symbol` can follow the current state in
329 * the ATN, otherwise `false`.
330 */
331 isExpectedToken(symbol: number): boolean;
332 get isMatchedEOF(): boolean;
333 /**
334 * Computes the set of input symbols which could follow the current parser
335 * state and context, as given by {@link #getState} and {@link #getContext},
336 * respectively.
337 *
338 * @see ATN#getExpectedTokens(int, RuleContext)
339 */
340 getExpectedTokens(): IntervalSet;
341 getExpectedTokensWithinCurrentRule(): IntervalSet;
342 /** Get a rule's index (i.e., `RULE_ruleName` field) or -1 if not found. */
343 getRuleIndex(ruleName: string): number;
344 get ruleContext(): ParserRuleContext;
345 /** Return List&lt;String&gt; of the rule names in your parser instance
346 * leading up to a call to the current rule. You could override if
347 * you want more details such as the file/line info of where
348 * in the ATN a rule is invoked.
349 *
350 * This is very useful for error messages.
351 */
352 getRuleInvocationStack(ctx?: RuleContext): string[];
353 /** For debugging and other purposes. */
354 getDFAStrings(): string[];
355 /** For debugging and other purposes. */
356 dumpDFA(): void;
357 get sourceName(): string;
358 get parseInfo(): Promise<ParseInfo | undefined>;
359 /**
360 * @since 4.3
361 */
362 setProfile(profile: boolean): Promise<void>;
363 /** During a parse is sometimes useful to listen in on the rule entry and exit
364 * events as well as token matches. This is for quick and dirty debugging.
365 */
366 set isTrace(trace: boolean);
367 /**
368 * Gets whether a {@link TraceListener} is registered as a parse listener
369 * for the parser.
370 */
371 get isTrace(): boolean;
372}