-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsast.ml
executable file
·79 lines (69 loc) · 2.38 KB
/
sast.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
(* Semantically-checked Abstract Syntax Tree *)
open Ast
type sexpr = typ * sx
and sx =
SLiteral of int
| SStrLiteral of string
| SFliteral of string
| SBoolLit of bool
| SId of string
| SBinop of sexpr * op * sexpr
| SUnop of uop * sexpr
| SAssign of string * sexpr
| SCall of string * sexpr list
| SNoexpr
type sstmt =
SBlock of sstmt list
| SExpr of sexpr
| SReturn of sexpr
| SIf of sexpr * sstmt * sstmt
| SFor of sexpr * sexpr * sexpr * sstmt
| SWhile of sexpr * sstmt
type sfunc_decl = {
styp : typ;
sfname : string;
sformals : bind list;
slocals : bind list;
sbody : sstmt list;
}
type sprogram = bind list * sfunc_decl list
(* Pretty-printing functions *)
let rec string_of_sexpr (t, e) =
"(" ^ string_of_typ t ^ " : " ^ (match e with
SLiteral(l) -> string_of_int l
| SStrLiteral(l) -> l
| SBoolLit(true) -> "true"
| SBoolLit(false) -> "false"
| SFliteral(l) -> l
| SId(s) -> s
| SBinop(e1, o, e2) ->
string_of_sexpr e1 ^ " " ^ string_of_op o ^ " " ^ string_of_sexpr e2
| SUnop(o, e) -> string_of_uop o ^ string_of_sexpr e
| SAssign(v, e) -> v ^ " = " ^ string_of_sexpr e
| SCall(f, el) ->
f ^ "(" ^ String.concat ", " (List.map string_of_sexpr el) ^ ")"
| SNoexpr -> ""
) ^ ")"
let rec string_of_sstmt = function
SBlock(stmts) ->
"{\n" ^ String.concat "" (List.map string_of_sstmt stmts) ^ "}\n"
| SExpr(expr) -> string_of_sexpr expr ^ ";\n";
| SReturn(expr) -> "return " ^ string_of_sexpr expr ^ ";\n";
| SIf(e, s, SBlock([])) ->
"if (" ^ string_of_sexpr e ^ ")\n" ^ string_of_sstmt s
| SIf(e, s1, s2) -> "if (" ^ string_of_sexpr e ^ ")\n" ^
string_of_sstmt s1 ^ "else\n" ^ string_of_sstmt s2
| SFor(e1, e2, e3, s) ->
"for (" ^ string_of_sexpr e1 ^ " ; " ^ string_of_sexpr e2 ^ " ; " ^
string_of_sexpr e3 ^ ") " ^ string_of_sstmt s
| SWhile(e, s) -> "while (" ^ string_of_sexpr e ^ ") " ^ string_of_sstmt s
let string_of_sfdecl fdecl =
"def " ^ string_of_typ fdecl.styp ^ " " ^
fdecl.sfname ^ "(" ^ String.concat ", " (List.map snd fdecl.sformals) ^
")\n{\n" ^
String.concat "" (List.map string_of_vdecl fdecl.slocals) ^
String.concat "" (List.map string_of_sstmt fdecl.sbody) ^
"}\n"
let string_of_sprogram (vars, funcs) =
String.concat "" (List.map string_of_vdecl vars) ^ "\n" ^
String.concat "\n" (List.map string_of_sfdecl funcs)