[antlr-interest] Could antlr do this ?

jbb at acm.org jbb at acm.org
Tue Apr 27 15:37:14 PDT 2004


On Tue, 27 Apr 2004 11:50:09 +0000, sun_yingwei at hotmail.com wrote:
>Hello everyone:
>
> Example for :
> "go from ab + 1 to dd - ( 2 +3 ) "
>the key is "go","from", "to"
>I want to get "ab + 1" and "dd - (2 + 3)". In fact, there are a lot 
>of commands like "go" and the combination of keys have a lot of 
>pattern. Can antlr do it?
>
>If it can do, who hava a sample for using antlr in VC++6.0 or web?
>
> Please help me.
>
>Thank you.
>
>-Freehawk

You aren't very specific about your language's rules, but here is a
stab at a sample parser and lexer - it is in java.

Hope this helps...

---------------CUT HERE---------------CUT HERE---------------
{ 
import java.io.*;
}

class freehawkParser extends Parser;

options {
    buildAST = true;
}

{
    public static void main(String[] args) {
	try {
	    freehawkLexer lexer =
		new freehawkLexer(new StringReader("go from ab + 1 to dd - ( 2 +3 )"));
	    freehawkParser parser = new freehawkParser(lexer);
	    parser.program();
	    antlr.CommonAST ast = (antlr.CommonAST)parser.getAST();
	    if (ast != null) {
		System.out.println("Parse result=`"+ast.toStringList()+"`");
	    } else {
		System.out.println("null AST");
	    }
	} catch(Exception e) {
	    System.err.println("exception: "+e);
	}
    }
}

program : statement EOF! ;

statement : GO_KW FROM_KW expression TO_KW expression ;

expression : term ( add_op term )* ;

term : factor ( mul_op factor )*;

factor :
      IDENTIFIER
    | NUMBER
    | LPARN expression RPARN
    ;

add_op : PLUS  | MINUS ;
mul_op : SPLAT | SLANT ;

class freehawkLexer extends Lexer;

tokens {
    GO_KW = "go";
    FROM_KW = "from";
    TO_KW = "to";
}

protected LETTER : 'a' .. 'z' | 'A' .. 'Z' ;
protected DIGIT : '0' .. '9' ;

IDENTIFIER options{ testLiterals = true; } : LETTER ( LETTER | DIGIT | '_' )* ;
NUMBER : ( DIGIT )+ ( '.' ( DIGIT )+ )? ;

PLUS : '+' ;
MINUS : '-' ;
SPLAT : '*' ;
SLANT : '/' ;
LPARN : '(' ;
RPARN : ')' ;

WS  : ( ' '|'\t') { $setType(Token.SKIP); };
EOL : ( '\r' ( '\n' )? | '\n' ) { newline(); $setType(Token.SKIP); };
---------------CUT HERE---------------CUT HERE---------------


 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/antlr-interest/

<*> To unsubscribe from this group, send an email to:
     antlr-interest-unsubscribe at yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/
 



More information about the antlr-interest mailing list