ANTLR ANother Tool for Language Recognition www antlr
- Slides: 17
ANTLR ANother Tool for Language Recognition www. antlr. org Jobson Ronan (jrjs) Renato Viana (rvf)
Motivação n n Parsers criados com YACC tendem a ter baixa qualidade de mensagens de erro Erros em gramáticas do YACC são difíceis de entender. YACC informa um erro de "shift/reduce" ou "reduce/reduce" associado a uma dada regra da gramática Possibilidade de gerar Parsers para várias linguagens (C++, Java, C# e Python) Open-source
Características n n n ANTLR gera recursive decent parsers e possui uma boa reportagem de erros. Parsers gerados pelo ANTLR são razoavelmente legíveis. Facilitando a depuração Possui boa documentação e grande quantidade de exemplos ¡ Apesar disso, a curva de aprendizagem ainda é grande.
Aprendendo por exemplo n Exp: Linguagem de expressões aritméticas ¡ ¡ n Suporta soma, subtração e multiplicação de inteiros Suporta parêntesis para definir prioridades Ex: ¡ ¡ ¡ 2+3 1 5*(3+7)
Gramática n Todas as gramáticas do ANTLR são subclasses de Lexer, Parser, or Tree. Parser ¡ As regras são específicadas em uma notação EBNF class Expr. Parser extends Parser; expr: ; mexpr : ; atom: | ; mexpr ((PLUS|MINUS) mexpr)* atom (STAR atom)* INT LPAREN expr RPAREN
Lexer class Expr. Lexer extends Lexer; options { k=2; // needed for newline junk char. Vocabulary='u 0000'. . 'u 007 F'; // allow ascii } LPAREN: RPAREN: PLUS : MINUS : STAR : INT : WS : ; '(' ; ')' ; '+' ; '-' ; '*' ; ('0'. . '9')+ ; ( ' ' | 'r' 'n' | 't' ) {$set. Type(Token. SKIP); }
Gerando n Executar ferramenta de geração $ java antlr. Tool expr. g n Resultado Expr. Lexer. java Expr. Parser. Token. Types. java
Testando n Executar o parser import antlr. *; public class Main { public static void main(String[] args) throws Exception { Expr. Lexer lexer = new Expr. Lexer(System. in); Expr. Parser parser = new Expr. Parser(lexer); parser. expr(); } }
Avaliando Expressões n Avaliando expressões on-the-fly class Expr. Parser extends Parser; expr returns [int value=0] {int x; } : value=mexpr ( PLUS x=mexpr {value += x; } | MINUS x=mexpr {value -= x; } )* ; mexpr returns [int value=0] {int x; } : value=atom ( STAR x=atom {value *= x; } )* ; atom returns [int value=0] : i: INT {value=Integer. parse. Int(i. get. Text()); } | LPAREN value=expr RPAREN ;
Testando n Alterações no método expr() import antlr. *; public class Main { public static void main(String[] args) throws Exception { Expr. Lexer lexer = new Expr. Lexer(System. in); Expr. Parser parser = new Expr. Parser(lexer); int x = parser. expr(); System. out. println(x); } }
Problemas n Mistura de interesses ¡ ¡ ¡ n Código de definição da gramática Código de definição das ações Código da linguagem alvo (Java) Solução ¡ Gerar uma AST
Gerando ASTs n Pequenas alterações na definição da gramática ¡ ¡ n Indica-se açucares sintáticos Indica-se nomes dos nós Define-se um Tree. Parser
Alterações na gramática n n “^” Índica as raízes das sub-arvores “!” Índica os açucares sintáticos class Expr. Parser extends Parser; options { build. AST=true; } expr: ; mexpr : ; atom: | ; mexpr ((PLUS^|MINUS^) mexpr)* atom (STAR^ atom)* INT LPAREN! expr RPAREN!
Definindo Tree. Parser class Expr. Tree. Parser extends Tree. Parser; options { import. Vocab=Expr. Parser; } expr returns [int r=0] { int a, b; } : #(PLUS a=expr b=expr) | #(MINUS a=expr b=expr) | #(STAR a=expr b=expr) | i: INT ; {r {r = = a+b; } a-b; } a*b; } (int)Integer. parse. Int(i. get. Text()); }
Testando import antlr. *; import antlr. collections. *; public class Main { public static void main(String[] args) throws Exception { Expr. Lexer lexer = new Expr. Lexer(System. in); Expr. Parser parser = new Expr. Parser(lexer); parser. expr(); AST t = parser. get. AST(); System. out. println(t. to. String. Tree()); Expr. Tree. Parser tree. Parser = new Expr. Tree. Parser(); int x = tree. Parser. expr(t); System. out. println(x); } }
Exercícios n 1. Adicionar a linguagem de expressões o comando print(4+3*6) n 2. Adicionar a linguagem de expressões suporte a varáveis v 1 = 3+5 print(v 1+10) *Não tente fazer os dois ao mesmo tempo
ANTLR ANother Tool for Language Recognition www. antlr. org Jobson Ronan (jrjs) Renato Viana (rvf)
- Language
- Antlr tree walker
- Rets client software
- Harris burdick pictures
- Another neat tool
- Another neat tool
- Kinect for windows speech recognition language pack
- Potter's tool is data cleaning tool
- Formuö
- Typiska novell drag
- Tack för att ni lyssnade bild
- Returpilarna
- Shingelfrisyren
- En lathund för arbete med kontinuitetshantering
- Särskild löneskatt för pensionskostnader
- Personlig tidbok
- Sura för anatom
- Vad är densitet