如何使用 Flex、Bison 正确解析不同部分的输入

How to parse input with different sections correctly with Flex, Bison

我正在尝试使用将文件作为输入的 Flex、Bison 编写编译器。文件包含算法行为的描述。文件有 2 个部分。

1. definition of registers, states
2. description of behavior

输入文件示例

registers = {state, temp,input}
states = {idle, done}

entity
    begin
        read(input)
        temp = input
        send(temp)
        become done
    end

我的问题如下
文件分为两部分。我需要查明被分析的输入是否属于正确的部分。例如,寄存器的定义 registers = {...} 不应放在实体的行为定义中。

我想到了这些解决方案。
1、在lex中用expression开头和结尾包裹正则表达式。例如,行为部分以 begin 开始,以 end 结束。所以基本上,如果我定义像 "begin.become.end" 这样的正则表达式,它应该正确解析 command become only when it is located between begin and end.
2. 为每个部分定义单独的带有表达式的 flex 文件。之后读取输入文件并使用一个带有表达式的 flex 文件对其进行解析,在编译器获取例如关键字 begin 之后,它将切换 flex 文件,其中包含用于解析行为的表达式。

我的问题是我提出的解决方案是否是解决问题的好方法,或者是否有更优雅和正确的方法来解决此类问题。

谢谢。

没有。你不需要为此乱搞词法分析器。只需在语法中定义它。这就是它的用途。

program
    : registers states entities
    ;

registers
    : REGISTERS '{' register_list '}'
    ;

register_list
    : register
    | register_list ',' register
    ;

// similarly for states

entities
    : entity
    | entities entity
    ;

entity
    : ENTITY BEGIN entity_stuff END
    ;

// etc, whatever entity_stuff can be, not including 'registers' or 'states'.

如果任何内容出现在错误的部分,将导致语法错误。

您可能希望允许 registersstates 以任一顺序出现(如果有意义),或者不出现或为空(同上)。留作 reader.

的练习