SDL 用法,第 4 部分:lex 和 yacc
构建用于脚本和 GUI 设计的语法分析器
构建用于脚本和 GUI 设计的语法分析器
Sam Lantinga 和 Lauren McDonell
Loki Entertainment Software
SkilledNursing.com
2000 年 5 月
内容: |
另一段 bison |
从基础开始 |
提供输入 |
将 lex 和 yacc 与 C++ 一起使用 |
从字符串分析 |
使用多个语法分析器 |
脚本语言 |
GUI 示例 |
结束语 |
参考资料 |
关于作者 |
在这部分中,我们将讨论所有 Linux 程序员工具库中的两种实用工具:lex 和 yacc。这些工具让我们轻松地构建了在我们基于 SDL 的 Linux 游戏 Pirates Ho! 中使用的脚本语言和 GUI 框架。
在设计 Pirates Ho! 时,我们需要一种简便的方法向玩家描述界面和对话框选项。我们需要简单、一致且灵活的语言来进行描述,因此我们寻找可以帮助我们构建脚本语言的工具。
谁想要另一段 bison?
我还在学校时,就已经对 "yacc" 这个词充满恐惧。它让我想到那些头发凌乱、面色苍白的学生低声念叨着编译器和符号表。所以我非常小心,尽量避免使用编译器类。但在开发游戏时,我鼓起勇气使用 yacc,希望它可以使编写脚本变得容易些。最后,yacc 不仅使编写脚本变得更容易,还使这个过程很有趣。
从基础开始
yacc 实际上非常易于使用。只要提供给它一组描述语法的规则,它就可以分析标记,并根据所见到的采取操作。对于我们使用的脚本语言,我们希望由浅入深,最初只是指定一些数字及其逻辑运算:
eval.y
%{ /* This first section contains C code which will be included in the output file. */ #include <stdlib.h> #include <stdio.h> /* Since we are using C++, we need to specify the prototypes for some internal yacc functions so that they can be found at link time. */ extern int yylex(void); extern void yyerror(char *msg); %} /* This is a union of the different types of values that a token can take on. In our case we'll just handle "numbers", which are of C int type. */ %union { int number; } /* These are untyped tokens which are recognized as part of the grammar */ %token AND OR EQUALS /* Here we are, any NUMBER token is stored in the number member of the union above. */ %token NUMBER /* These rules all return a numeric value */ %type expression %type logical_expression and or equals %% /* Our language consists either of a single statement or of a list of statements. Notice the recursivity of the rule, this allows us to have any number of statements in a statement list. */ statement_list: statement | statement_list statement ; /* A statement is simply an expression. When the parser sees an expression we print out its value for debugging |