[antlr-interest] ANTLR Source Formatting

Hendrik Maryns qwizv9b02 at sneakemail.com
Wed Nov 26 05:52:30 PST 2008


Edgar Espina schreef:
> Hi all,
> 
> I would like to include a source formatter in ANTLR IDE.
> 
> Can anyone suggest a default format?

Since nobody of the more experienced people here has answered, let me
present what I have come up with in my short history with ANTLR:

/**
 * There are 6 kinds of formulas.
 */
body returns [Formula result]
	: labelFormula
		{ $result = $labelFormula.result; }
	| atomic
		{ $result = $atomic.result; }
	| unary
		{ $result = $unary.result; }
	| binary
		{ $result = $binary.result; }
	| n_ary
		{ $result = $n_ary.result; }
	| quantor
		{ $result = $quantor.result; }
	;

That is: the rulename and returns statement on one line, the colon on
the next, then each alternative on its own line with the pipes aligned
to the colon.  Code blocks in a separate line, with an additional
indent.  (This will not always be possible, see below.)  Then the
semicolon aligned with the colon and pipes on its own line.  I use tabs
for indentation because I like them, there should of course be an option
to use spaces.

n_aryArguments returns [List<Formula> result]
@init{ $result = new ArrayList<Formula>(); }
	: ( WHITESPACE arg=formula { $result.add(arg); } )+
	;

@init and other such stuff on a separate line, without indentation.
Here you see that it is difficult to put code blocks on a separate line,
since it is inside the ()+.  You could however do

	: (
	    WHITESPACE arg=formula
	    	 { $result.add(arg); }
	  )+
	;

for consistency.

Another one with parens:

equality returns [Formula result]
	: EQUALITY WHITESPACE
		  ( firstfirst=firstOrderVariable WHITESPACE
secondfirst=firstOrderVariable
			{ $result = new FirstOrderEquality($firstfirst.result,
$secondfirst.result); } )
		| ( firstsecond=secondOrderVariable WHITESPACE
secondsecond=secondOrderVariable
			{ $result = new SecondOrderEquality($firstsecond.result,
$secondsecond.result); } )
	;

Note the parens are aligned, the pipe is before it.  Maybe here it would
make sense to have the parens on their own line as well.

And of course all of this should be configurable, similar to the Java
formatter.  Have fun :-)

Cheers, H.
-- 
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 257 bytes
Desc: OpenPGP digital signature
Url : http://www.antlr.org/pipermail/antlr-interest/attachments/20081126/cd19e9c6/attachment.bin 


More information about the antlr-interest mailing list