From bdda174af64a4a325ccfb0c7f721b2c3b4f4c701 Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Sun, 25 Mar 2012 07:43:54 -0500 Subject: [PATCH] Set stop token even when RecognitionException occurs. Add ParserRuleContext.exception field to hold exception if one occurs. Resolves antlr/antlr4#49. --- runtime/Java/src/org/antlr/v4/runtime/Parser.java | 2 ++ .../Java/src/org/antlr/v4/runtime/ParserRuleContext.java | 6 ++++++ .../org/antlr/v4/tool/templates/codegen/Java/Java.stg | 4 ++-- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/runtime/Java/src/org/antlr/v4/runtime/Parser.java b/runtime/Java/src/org/antlr/v4/runtime/Parser.java index 66c234f3c..3430fc628 100644 --- a/runtime/Java/src/org/antlr/v4/runtime/Parser.java +++ b/runtime/Java/src/org/antlr/v4/runtime/Parser.java @@ -386,6 +386,7 @@ public abstract class Parser extends Recognizer } public void exitRule() { + _ctx.stop = _input.LT(-1); // trigger event on _ctx, before it reverts to parent if ( _parseListeners != null) triggerExitRuleEvent(); _ctx = (ParserRuleContext)_ctx.parent; @@ -411,6 +412,7 @@ public abstract class Parser extends Recognizer } public void unrollRecursionContexts(ParserRuleContext _parentctx) { + _ctx.stop = _input.LT(-1); ParserRuleContext retctx = _ctx; // save current ctx (return value) // unroll so _ctx is as it was before call to recursive method diff --git a/runtime/Java/src/org/antlr/v4/runtime/ParserRuleContext.java b/runtime/Java/src/org/antlr/v4/runtime/ParserRuleContext.java index 3ba0bb249..23928bc6d 100644 --- a/runtime/Java/src/org/antlr/v4/runtime/ParserRuleContext.java +++ b/runtime/Java/src/org/antlr/v4/runtime/ParserRuleContext.java @@ -109,6 +109,12 @@ public class ParserRuleContext extends RuleContext { /** Set during parsing to identify which alt of rule parser is in. */ public int altNum; + /** + * The exception which forced this rule to return. If the rule successfully + * completed, this is {@code null}. + */ + public RecognitionException exception; + public ParserRuleContext() { } /** COPY a ctx (I'm deliberately not using copy constructor) */ diff --git a/tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg b/tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg index 422e4ac3d..7fb374f6c 100644 --- a/tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg +++ b/tool/resources/org/antlr/v4/tool/templates/codegen/Java/Java.stg @@ -229,11 +229,11 @@ RuleFunction(currentRule,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAc int _alt; - _localctx.stop = _input.LT(-1); } catch (RecognitionException re) { + _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } @@ -265,11 +265,11 @@ LeftRecursiveRuleFunction(currentRule,code,locals,ruleCtx,altLabelCtxs, int _alt; - _localctx.stop = _input.LT(-1); } catch (RecognitionException re) { + _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); }