[antlr-interest] Catching errors

Dimitrios Kolovos dskolovos at gmail.com
Wed Dec 7 07:02:24 PST 2005


Hi Peter,

Just add the following (or similar) code in your parser and lexer in the 
.g file (fragement taken from OCL.g)

	private Vector errors = new Vector();
	private Vector warnings = new Vector();
	
	/**@return The number of errors found in the parser*/
	public int errorNumber(){
		return errors.size();
	}
	
	/**@return The number of warnings found in the parser*/
	public int warningNumber(){
		return warnings.size();
	}
	
	/**@return All errors messages found in the parser*/
	public String [] errors () {
		String [] ret = new String [errors.size()];
		for (int i = 0; i < ret.length; ++i)
			ret[i] = (String)errors.elementAt(i);
		return ret;
	}
	
	/**@return All warning messages found in the parser*/
	public String [] warnings () {
		String [] ret = new String [warnings.size()];
		for (int i = 0; i < ret.length; ++i)
			ret[i] = (String)warnings.elementAt(i);
		return ret;
	}

	public void reportError(RecognitionException ex) {
		errors.addElement(ex.getMessage());
	}
	
	public void reportError(String s) {
		errors.addElement(s);
	}
	
	public void reportWarning(String s) {
		warnings.addElement(s);
	}

Cheers,
Dimitrios

Peter Kronenberg wrote:

> How can I trap parsing errors from Antlr?  When there is a syntax 
> error in the expression, I get something like this on System.err:
>
> line 1:16: unexpected token: 80
>
> But in my Java code, the call to the parser returns with no errors. 
> The only indication that there is a problem is that parser.getAST() 
> returns null.  So I can detect that there is an error, but I'd like to 
> be able to trap the text of the error so I can display it properly in 
> the client.
>
>
> Peter Kronenberg
> Software Engineer
> (703) 885-1222
> pkronenberg at technicacorp.com
>
> The information contained in this transmission may contain privileged 
> and confidential information. It is intended only for the use of the 
> person(s) named above. If you are not the intended recipient, you are 
> hereby notified that any review, dissemination, distribution or 
> duplication of this communication is strictly prohibited. If you are 
> not the intended recipient, please contact the sender by reply e-mail 
> and destroy all copies of the original message. Technica Corporation 
> does not represent this e-mail to be free from any virus, fault or 
> defect and it is therefore the responsibility of the recipient to 
> first scan it for viruses, faults and defects. To reply to our e-mail 
> administrator directly, please send an e-mail to 
> postmaster at technicacorp.com <mailto:postmaster at technicacorp.com>. 
> Thank you.
>
>  
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20051207/4c280fb1/attachment.html


More information about the antlr-interest mailing list