yacc中的Lisp语法 [英] Lisp grammar in yacc

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

问题描述

我正在尝试建立Lisp语法.容易吧?显然不是.

I am trying to build a Lisp grammar. Easy, right? Apparently not.

我提供这些输入并收到错误信息...

I present these inputs and receive errors...

( 1 1)
23 23 23 
ui ui

这是语法...

%%
sexpr: atom                 {printf("matched sexpr\n");}
    | list
    ;
list: '(' members ')'       {printf("matched list\n");}
    | '('')'                {printf("matched empty list\n");}
    ;
members: sexpr              {printf("members 1\n");}
    | sexpr members         {printf("members 2\n");}
    ;
atom: ID                    {printf("ID\n");}
    | NUM                   {printf("NUM\n");}
    | STR                   {printf("STR\n");}
    ;
%%

据我所知,我需要一个定义为程序的非终端程序,整个分析树都可以挂在该程序上.但是我尝试了一下,但似乎没有用.

As near as I can tell, I need a single non-terminal defined as a program, upon which the whole parse tree can hang. But I tried it and it didn't seem to work.

编辑-这是我的顶级终端"方法:

edit - this was my "top terminal" approach:

program: slist;

slist: slist sexpr | sexpr;

但是它允许出现以下问题:

But it allows problems such as:

( 1 1 

Edit2:FLEX代码是...

The FLEX code is...

%{
    #include <stdio.h>
    #include "a.yacc.tab.h"
    int linenumber;
    extern int yylval;
%}
%%
\n                         { linenumber++; }
[0-9]+                     { yylval = atoi(yytext); return NUM; }
\"[^\"\n]*\"               { return STR; }
[a-zA-Z][a-zA-Z0-9]*       { return ID; }
.
%%

过度匹配的示例...

An example of the over-matching...

(1 1 1)
NUM
matched sexpr
NUM
matched sexpr
NUM
matched sexpr
(1 1
NUM
matched sexpr
NUM
matched sexpr

这是什么错误?

错误在于词法分析器中.

edit: The error was in the lexer.

推荐答案

错误确实在词法分析器中.括号最后为".在词法分析器中,并且不会在分析器中显示为括号.

The error is really in the lexer. Your parentheses end up as the last "." in the lexer, and don't show up as parentheses in the parser.

添加类似的规则

\)     { return RPAREN; }
\(     { return LPAREN; }

到词法分析器,然后将解析器中所有出现的'(',')'分别更改为LPAREN和RPAREN. (此外,您需要在定义令牌列表的地方#define LPAREN和RPAREN)

to the lexer and change all occurences of '(', ')' to LPAREN and RPAREN respectively in the parser. (also, you need to #define LPAREN and RPAREN where you define your token list)

注意:我不确定语法,可能是反斜杠错误了.

Note: I'm not sure about the syntax, could be the backslashes are wrong.

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

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