【问题标题】:How to deal with the declaration of variables in a parser.mly?如何处理 parser.mly 中的变量声明?
【发布时间】:2011-06-27 16:38:37
【问题描述】:

我正在用 Ocaml 编写一个 mini-pascal 编译器。例如,我希望我的编译器接受以下代码:

program test;
var
   a,b : boolean;
   n : integer;
begin
   ...
end.

我在处理变量声明时遇到了困难(var 之后的部分)。目前,变量的类型在sib_syntax.ml中是这样定义的:

type s_var =
    { s_var_name: string;
      s_var_type: s_type; }

这里是sib_parser.mly。我的问题是,我可以在哪里以及如何告诉编译器构建globals,即变量声明,它实际上是s_var 的列表。 sib_parser.mly(terminated_bindings,binding,separated_nonempty_list,等等)结尾的menhir部分我想我需要提炼一下,但是我不知道怎么...

有人可以帮忙吗?非常感谢!

【问题讨论】:

    标签: compiler-construction ocaml parser-generator


    【解决方案1】:

    从外观上看,在您的绑定规则中,您可以访问ids,这是一个变量名列表,因此您可以编写,例如:

    binding:
      | ids = separated_nonempty_list(COMMA, IDENT) COLON INTEGER
          { List.map (fun id -> { s_var_name = id ; s_var_type = St_int}) ids }
      | ids = separated_nonempty_list(COMMA, IDENT) COLON BOOLEAN
          { List.map (fun id -> { s_var_name = id ; s_var_type = St_bool}) ids }
    

    这将使binding 规则返回s_var list

    【讨论】:

    • 非常感谢,这很有帮助。往前走,我已经发布了另一个相关的thread,如果你想看看...
    猜你喜欢
    • 2012-10-22
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 2012-06-03
    • 2016-03-09
    • 1970-01-01
    • 2021-03-15
    • 2018-11-08
    相关资源
    最近更新 更多