[antlr-interest] Enforcing that a statement parm is only specified one time

Jim Idle jimi at temporal-wave.com
Wed Oct 29 13:45:44 PDT 2008


On Wed, 2008-10-29 at 16:12 -0400, Brisard, Fred D wrote:

> Is there a standard pattern for allowing a single instance of a phrase
> on a given statement?
> 
> For example, I have statement of the syntax of
> 
> Stmtname [keyword1 keyvalue1] [keyword2 keyvalue2]
> 
> I want to allow keyword1 or keyword2 to be specified in any order but
> I don’t want to allow the specification of either keyword more than
> once.
> 
> I have some statements with up to 8 different keywords that should
> only occur once but in any order.


Use semantic errors for this as the feedback to the users is much better
than "Syntax error at...". 

Lots of ways to do it but something like (not checked for syntax, just
typed into the email):

keyWordSet

Scope {
 int key1;
 int key2; // etc
}
@init
{
   $keyWordSet::key1 = 0;
  $keyWordSet::key2 = =
  // etc
}
: keywords*
;

keywords
 : KEY1 { if ( $keyWordSet::key1++ > 1) { myErrorHandler(E_TOO_MANY,
$KEY1); }
 | etc


Probably better to do this in the AST parser if you are using one. Your
error will then say:

Error: line 2, offset nn : You can only specify 'flort' once in this
construct.
blah blah flort blah blah flort
                          ^

If you want to be clever, you can record the first location in the scope
and indicate where it was first specified. You could also classify such
things as warnings rather than errors as saying the same thing twice or
more just confirms that is what they want:

Warning line 2, offset nn : You have said 'plumber' 12 times in the same
construct. Are you campaigning?
wink joe the plumber plumber joe wink joe the bloody plumber plumber
plumber
                     ^                               ^       ^       ^


Basically, for anything other than a one off script parser or something,
never try to do things like this in the grammar itself, ALWAYS accept
anything that is vaguely legal, count or flag what is present, then give
specific errors. Similar things include:

Error: line 2, offset nn : You cannot combine 'baseball' and 'obama' in
the same timeslot.
schedule blah blah obama blah blah baseball
                                   ^

Rather than:

Syntax error near 'baseball', perhaps you meant a real sport like
'cricket'?

And so on.


Jim
 

> 
> Thanks for any suggestions.
> 
> 
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20081029/a0aaf151/attachment.html 


More information about the antlr-interest mailing list