超出程序结束的语法错误

a_m*_*m0d 4 ocaml

我正在尝试用ocaml编写一个玩具编译器.目前,我正试图为我的词法分析器实施越位规则.但是,我在使用ocaml语法时遇到了一些麻烦(编译器错误非常缺乏信息).下面的代码(33行)导致第34行出错,超出了源代码的末尾.我不确定是什么导致了这个错误.

open Printf

let s = (Stack.create():int Stack.t);

let rec check x =
    (
        if Stack.is_empty s then
            Stack.push x s
        else if Stack.top s < x then
            (
                Stack.push x s;
                printf "INDENT\n";
            )
        else if Stack.top s > x then
            (
                printf "DEDENT\n";
                Stack.pop s;
                check x;
            )
        else
            printf "MATCHED\n";
     );

let main () =
    (
        check 0;
        check 4;
        check 6;
        check 8;
        check 5;
    );

let _ = Printexc.print main ()
Run Code Online (Sandbox Code Playgroud)

Ocaml输出:

File "lexer.ml", line 34, characters 0-0:
Error: Syntax error
Run Code Online (Sandbox Code Playgroud)

有人可以帮我弄清楚错误是由什么引起的,并帮助我修复它吗?

blt*_*txd 10

尾随; main,checks的定义之后是错误的.

;;替换这3个出现.如下:

let s = (Stack.create():int Stack.t);;

let rec check x =
  (
      (* ...sequence of imperative statements... *)
  );;

let main () =
  (
      (* ...sequence of imperative statements... *)
  );;
Run Code Online (Sandbox Code Playgroud)


; 用于以下情况:

  • 对命令性陈述进行排序
  • 作为列表元素之间的分隔符
  • 作为数组元素之间的分隔符
  • 作为记录字段之间的分隔符


一些例子:

let hello_world1 () =
  print_endline "Hello";
  print_endline "World !"
;;

let hello_world2 () =
  begin
    print_endline "Hello";
    print_endline "World !"
  end
;;

let hello_world3 () =
  (
    print_endline "Hello";
    print_endline "World !";
  )
;;

let some_list =
  [1; 2; 3]
;;

let some_array =
  [| 'a'; 'b'; 'c' |]
;;

type my_process =
  {
    pid: int;
    executable_path: string;
  }
;;

let p1 = { pid = 142; executable_path = "./my_exec" };;
Run Code Online (Sandbox Code Playgroud)

  • 虽然在这种特殊情况下,所有这些双分号都是可选的,因为您的文件都是定义.只有当你在顶层有一个简单的陈述时,你才需要在它之前有一个双分号 (3认同)