在 Antlr 中定义语法 [英] define a grammar in Antlr

查看:16
本文介绍了在 Antlr 中定义语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了以下语法.

I have defined the following grammar.

grammar Sample_1;


@header {
  package a;
}

@lexer::header {
  package a;
}

program
    :   
        define*
        implement*
    ;


define
    :   IDENT '=(' INTEGER',' INTEGER ')'
    ;

implement
    :IDENT '=(' (IDENT ','?)* ')'
    ;

fragment LETTER : ('a'..'z' | 'A'..'Z') ;
fragment DIGIT : '0'..'9';
INTEGER : DIGIT+ ;
IDENT : LETTER (LETTER | DIGIT)*;
WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;};
COMMENT : '//' .* ('\n'|'\r') {$channel = HIDDEN;};

如何检查这个语法,以便当我有例子时

How to check in this grammar so that when I have the example

A=(1,1)
B=(1,2)

G=(A,B)

结果成功但是如果我写

A=(1,1)
B=(1,2)

G=(A,E)

它给出了 E 未定义的错误谢谢

it gives an error that E is not defined thanks

结果:非常感谢:

grammar Sample_1;

@members{
    int level=0;
}

@header {
  package a;
}

@lexer::header {
  package a;
}

program
    :   
        block
    ;
block   
scope {
    List symbols;
}
@init {
    $block::symbols=new ArrayList();
    level++;
}
@after { 
     System.err.println("Hello");
     level--;
 }
    : (define* implement+)
    ;

define
    :   IDENT {$block::symbols.add($IDENT.text);} '=(' INTEGER',' INTEGER ')' 
    ;

implement
    :IDENT '=(' (a=IDENT 
    {if (!$block::symbols.contains($a.text)){
    System.err.println("undefined");
    }}','?)* ')'
    ;

fragment LETTER : ('a'..'z' | 'A'..'Z') ;
fragment DIGIT : '0'..'9';
INTEGER : DIGIT+ ;
IDENT : LETTER (LETTER | DIGIT)*;
WS : (' ' | '\t' | '\n' | '\r' | '\f')+ {$channel = HIDDEN;};
COMMENT : '//' .* ('\n'|'\r') {$channel = HIDDEN;};

推荐答案

Antlr 支持 actions,即嵌入在语法文件中的小代码片段.

Antlr supports actions, little snippets of code embedded in the grammar file.

任务的操作可以存储到地图中.右侧 IDENT 的操作可能会尝试从地图中提取值,如果失败则抛出异常.

An action for an assignment could store into a map. An action for a right-hand-side IDENT could try to pull a value from the map, and throw an exception if it fails.

Terrence Parr 的权威 ANTLR 参考"中的第 6 章涵盖了操作.

Chapter 6 in Terrence Parr's "The Definitive ANTLR Reference" covers actions.

这篇关于在 Antlr 中定义语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆