Syntax error outside program

I am experimenting with writing a toy compiler in ocaml. I am currently trying to follow the offside rule for my lexer. However, I am having some problems with ocaml syntax (compiler errors are extremely uninformative). The code below (33 lines) causes an error on line 34, outside the source code. I am not sure what causes this error.

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 ()

Ocaml Output:

File "lexer.ml", line 34, characters 0-0:
Error: Syntax error

Can someone help me figure out what is causing the error and help me on the way to fixing it?

+3
source share
2 answers

Ultimate ; after the definitions of main, check and s are erroneous.

3 ;; :

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

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

let main () =
  (
      (* ...sequence of imperative statements... *)
  );;


; :


:

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" };;
+9

; :

open Printf

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

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 ()

:

gaius@debian:~/Projects/TestCase$ ./lexer 
INDENT
INDENT
INDENT
DEDENT
DEDENT
INDENT
+2

Source: https://habr.com/ru/post/1738325/


All Articles