Lex,Yacc和EBNF规范 [英] Lex and Yacc and EBNF specification

查看:261
本文介绍了Lex,Yacc和EBNF规范的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只想检查一种语言的语法是否正确, 使用yacc编写语法分析器的简单方法是什么?

if I just want to check whether the syntax of a language is correct or not, what is the easy way of writing a syntax analyzer using yacc.

推荐答案

请注意,用于EBNF的ISO标准是ISO 14977:1996,您在问题中使用的"EBNF"与标准版本具有有限的相似之处.这使我们不得不解释您的语法规则.

Note that the ISO standard for EBNF is ISO 14977:1996 and the 'EBNF' you've used in the question bears limited resemblance to the standard version. That leaves us having to interpret your grammar rule.

  • 所有非小写字母都用单个单词写成非终结符.
  • 端子以大写形式写成单个单词.
  • 冒号用于将非终结符与其定义分开.
  • 点(句点)用于标记规则的结束.
  • 方括号包含可选的材料(零或一次).

牢记这些定义,您需要:

With those definitions in mind, you need:

  • 将DECLARATION,OF,CONST,VAR,END识别为终端(关键字)的词法分析器.
  • 一种语法,其中包含用于声明单位,标识,const_declaration,var_declaration,procedure_interface,function_interface的规则.

给出:

%token DECLARATION
%token OF
%token CONST
%token VAR
%token END

%%

declaration_unit
    :   DECLARATION OF ident opt_const_declaration opt_var_declaration
        opt_procedure_interface opt_function_interface DECLARATION END
    ;

opt_const_declaration
    :   /* Nothing */
    |   CONST const_declaration
    ;

opt_var_declaration
    :   /* Nothing */
    |   VAR var_declaration
    ;

opt_procedure_interface
    :   /* Nothing */
    |   procedure_interface
    ;

opt_function_interface
    :   /* Nothing */
    |   function_interface
    ;

您现在只需填写identconst_declarationvar_declarationprocedure_interfacefunction_interface的规则.

You now just have to fill in the rules for ident, const_declaration, var_declaration, procedure_interface, function_interface.

对于简单的语法检查,您可以为尚未完全定义的语法部分添加占位符和规则.例如,您可以添加:

For simple syntax checking, you could add placeholder tokens and rules for the parts of the grammar that you've not yet fully defined. For example, you might add:

%token IDENT
%token CONST_DECLARATION
%token VAR_DECLARATION
%token PROCEDURE_INTERFACE
%token FUNCTION_INTERFACE

ident
    :   IDENT
    ;

const_declaration
    :   CONST_DECLARATION
    ;

var_declaration
    :   VAR_DECLARATION
    ;

procedure_interface
    :   PROCEDURE_INTERFACE
    ;

function_interface
    :   FUNCTION_INTERFACE
    ;

您的词法分析器只需要能够可靠地识别那些虚拟标记,直到您提供正确的规则即可.

Your lexical analyzer simply needs to be able to recognize those dummy tokens reliably until you provide the correct rules.

这篇关于Lex,Yacc和EBNF规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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