[antlr-interest] Antlr newbie trying to make Sloc counter with antlr
Bart Kiers
bkiers at gmail.com
Fri Feb 25 07:50:37 PST 2011
Hi Troy,
On Fri, Feb 25, 2011 at 4:36 PM, tjtaill36 <tjtaill36 at gmail.com> wrote:
> Bart,
>
> Thanks for answering a sloc is a logical line of code in a c base language
> that is pretty much the number of non commented semi colons.
>
>
Ah, I see.
> this is my test code and it says there is 0 slocs when it should answer two
>
> package code.metrics;
>
> import java.io.IOException;
>
> import org.antlr.runtime.ANTLRStringStream;
> import org.antlr.runtime.CommonTokenStream;
> import org.antlr.runtime.RecognitionException;
>
>
> public class CountSlocs {
> public static void main(String[] args) throws IOException,
> RecognitionException {
>
> StringBuilder file = new StringBuilder();
> file.append("package code.metrics;\n");
> file.append("/* ml comment */\n");
> file.append("class Whatever {\n");
> file.append("\tpublic static void main(String[] args){\n");
> file.append("\t\tSystem.out.println(\"Hello World!\");\n");
> file.append("\t}\n");
> file.append("}\n");
>
> ANTLRStringStream in = new ANTLRStringStream(file.toString());
> Slocs lexer = new Slocs(in);
>
> CommonTokenStream tokens = new CommonTokenStream(lexer);
>
> tokens.getTokens();
>
> System.out.println(lexer.slocs);
> }
>
> }
>
> Troy
When I run your code, I get this:
$ java -cp antlr-3.2.jar org.antlr.Tool Slocs.g
$ javac -cp antlr-3.2.jar *.java
$ java -cp .:antlr-3.2.jar CountSlocs
2
which is the expected output...
Note that since you're using the `filter=true` option, you don't need to
account for anything except those token you're interested in. So all the
`.*` stuff can be omitted. The following grammar also produces "2" being
printed to the console:
lexer grammar Slocs;
// options
// members
COMMENT
: '/*' .* '*/'
| '//' ~('\r' | '\n')*
;
// string and char-literals here
SLOC
: ';' {slocs++;}
;
Regards,
Bart.
More information about the antlr-interest
mailing list