util.ml 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. open Printf
  2. open Str
  3. open Lexing
  4. open Types
  5. (** Empty location, use when node location is unkown or irrelevant. *)
  6. let noloc = ("", 0, 0, 0, 0)
  7. let rec repeat s n = if n < 1 then "" else s ^ (repeat s (n - 1))
  8. let expand n text = text ^ repeat " " (n - String.length text)
  9. (* Logging functions *)
  10. let hline = "-----------------------------------------------------------------"
  11. let prt_node node = prerr_endline (Stringify.node2str node)
  12. let log_plain_line verbosity line =
  13. if Globals.args.verbose >= verbosity then prerr_endline line
  14. let log_line verbosity line =
  15. log_plain_line verbosity (repeat " " 13 ^ line)
  16. let log_node verbosity node =
  17. if Globals.args.verbose >= verbosity then prt_node node
  18. (* Variable generation *)
  19. let var_counter = ref 0
  20. let fresh_var prefix =
  21. var_counter := !var_counter + 1;
  22. prefix ^ "$" ^ string_of_int !var_counter
  23. (* Constants are marked by a double $$ for recognition during constant
  24. * propagation *)
  25. let fresh_const prefix = fresh_var (prefix ^ "$")
  26. let loc_from_lexpos pstart pend =
  27. let (fname, ystart, yend, xstart, xend) = begin
  28. pstart.pos_fname,
  29. pstart.pos_lnum,
  30. pend.pos_lnum,
  31. (pstart.pos_cnum - pstart.pos_bol + 1),
  32. (pend.pos_cnum - pend.pos_bol)
  33. end in
  34. if ystart = yend && xend < xstart then
  35. (fname, ystart, yend, xstart, xstart)
  36. else
  37. (fname, ystart, yend, xstart, xend)
  38. let rec flatten_blocks lst =
  39. let flatten = flatten_blocks in
  40. let rec trav = function
  41. | Block body ->
  42. Block (flatten body)
  43. | FunDef (export, ret_type, name, params, body, ann) ->
  44. FunDef (export, ret_type, name, flatten params, trav body, ann)
  45. | If (cond, body, ann) ->
  46. If (cond, trav body, ann)
  47. | IfElse (cond, tbody, fbody, ann) ->
  48. IfElse (cond, trav tbody, trav fbody, ann)
  49. | While (cond, body, ann) ->
  50. While (cond, trav body, ann)
  51. | DoWhile (cond, body, ann) ->
  52. DoWhile (cond, trav body, ann)
  53. | For (counter, start, stop, step, body, ann) ->
  54. For (counter, start, stop, step, trav body, ann)
  55. | VarDecs decs ->
  56. VarDecs (flatten decs)
  57. | LocalFuns decs ->
  58. LocalFuns (flatten decs)
  59. | node -> node
  60. in
  61. match lst with
  62. | [] -> []
  63. | Block nodes :: tl -> flatten nodes @ (flatten tl)
  64. | DummyNode :: tl -> flatten tl
  65. | hd :: tl -> trav hd :: (flatten tl)
  66. (* Default tree transformation
  67. * (node -> node) -> node -> node *)
  68. let transform_children trav node =
  69. let trav_all nodes = List.map trav nodes in
  70. match node with
  71. | Program (decls, ann) ->
  72. Program (flatten_blocks (trav_all decls), ann)
  73. | FunDec (ret_type, name, params, ann) ->
  74. FunDec (ret_type, name, trav_all params, ann)
  75. | FunDef (export, ret_type, name, params, body, ann) ->
  76. FunDef (export, ret_type, name, trav_all params, trav body, ann)
  77. | GlobalDec (ctype, name, ann) ->
  78. GlobalDec (ctype, name, ann)
  79. | GlobalDef (export, ctype, name, Some init, ann) ->
  80. GlobalDef (export, ctype, name, Some (trav init), ann)
  81. | VarDecs decs ->
  82. VarDecs (trav_all decs)
  83. | LocalFuns funs ->
  84. LocalFuns (trav_all funs)
  85. | VarDec (ctype, name, Some init, ann) ->
  86. VarDec (ctype, name, Some (trav init), ann)
  87. | Assign (name, None, value, ann) ->
  88. Assign (name, None, trav value, ann)
  89. | Assign (name, Some dims, value, ann) ->
  90. Assign (name, Some (trav_all dims), trav value, ann)
  91. | VarLet (dec, None, value, ann) ->
  92. VarLet (dec, None, trav value, ann)
  93. | VarLet (dec, Some dims, value, ann) ->
  94. VarLet (dec, Some (trav_all dims), trav value, ann)
  95. | Return (value, ann) ->
  96. Return (trav value, ann)
  97. | If (cond, body, ann) ->
  98. If (trav cond, trav body, ann)
  99. | IfElse (cond, true_body, false_body, ann) ->
  100. IfElse (trav cond, trav true_body, trav false_body, ann)
  101. | While (cond, body, ann) ->
  102. While (trav cond, trav body, ann)
  103. | DoWhile (cond, body, ann) ->
  104. DoWhile (trav cond, trav body, ann)
  105. | For (counter, start, stop, step, body, ann) ->
  106. For (counter, trav start, trav stop, trav step, trav body, ann)
  107. | Allocate (dec, dims, ann) ->
  108. Allocate (dec, trav_all dims, ann)
  109. | Expr value ->
  110. Expr (trav value)
  111. | Block (body) ->
  112. Block (trav_all body)
  113. | Monop (op, value, ann) ->
  114. Monop (op, trav value, ann)
  115. | Binop (op, left, right, ann) ->
  116. Binop (op, trav left, trav right, ann)
  117. | Cond (cond, true_expr, false_expr, ann) ->
  118. Cond (trav cond, trav true_expr, trav false_expr, ann)
  119. | TypeCast (ctype, value, ann) ->
  120. TypeCast (ctype, trav value, ann)
  121. | FunCall (name, args, ann) ->
  122. FunCall (name, trav_all args, ann)
  123. | Arg value ->
  124. Arg (trav value)
  125. | ArrayInit (value, dims) ->
  126. ArrayInit (trav value, dims)
  127. | Var (dec, Some dims, ann) ->
  128. Var (dec, Some (trav_all dims), ann)
  129. | VarUse (dec, Some dims, ann) ->
  130. VarUse (dec, Some (trav_all dims), ann)
  131. | FunUse (dec, params, ann) ->
  132. FunUse (dec, trav_all params, ann)
  133. | _ -> node
  134. let annotate a = function
  135. | Program (decls, ann) ->
  136. Program (decls, a :: ann)
  137. | FunDec (ret_type, name, params, ann) ->
  138. FunDec (ret_type, name, params, a :: ann)
  139. | FunDef (export, ret_type, name, params, body, ann) ->
  140. FunDef (export, ret_type, name, params, body, a :: ann)
  141. | GlobalDec (ctype, name, ann) ->
  142. GlobalDec (ctype, name, a :: ann)
  143. | GlobalDef (export, ctype, name, init, ann) ->
  144. GlobalDef (export, ctype, name, init, a :: ann)
  145. | VarDec (ctype, name, init, ann) ->
  146. VarDec (ctype, name, init, a :: ann)
  147. | Assign (name, dims, value, ann) ->
  148. Assign (name, dims, value, a :: ann)
  149. | VarLet (dec, dims, value, ann) ->
  150. VarLet (dec, dims, value, a :: ann)
  151. | Return (value, ann) ->
  152. Return (value, a :: ann)
  153. | If (cond, body, ann) ->
  154. If (cond, body, a :: ann)
  155. | IfElse (cond, true_body, false_body, ann) ->
  156. IfElse (cond, true_body, false_body, a :: ann)
  157. | While (cond, body, ann) ->
  158. While (cond, body, a :: ann)
  159. | DoWhile (cond, body, ann) ->
  160. DoWhile (cond, body, a :: ann)
  161. | For (counter, start, stop, step, body, ann) ->
  162. For (counter, start, stop, step, body, a :: ann)
  163. | Allocate (dec, dims, ann) ->
  164. Allocate (dec, dims, a :: ann)
  165. | Monop (op, value, ann) ->
  166. Monop (op, value, a :: ann)
  167. | Binop (op, left, right, ann) ->
  168. Binop (op, left, right, a :: ann)
  169. | Cond (cond, true_expr, false_expr, ann) ->
  170. Cond (cond, true_expr, false_expr, a :: ann)
  171. | TypeCast (ctype, value, ann) ->
  172. TypeCast (ctype, value, a :: ann)
  173. | FunCall (name, args, ann) ->
  174. FunCall (name, args, a :: ann)
  175. | Arg value ->
  176. Arg (value)
  177. | Var (dec, dims, ann) ->
  178. Var (dec, dims, a :: ann)
  179. | VarUse (dec, dims, ann) ->
  180. VarUse (dec, dims, a :: ann)
  181. | FunUse (dec, params, ann) ->
  182. FunUse (dec, params, a :: ann)
  183. | Const (BoolVal value, ann) ->
  184. Const (BoolVal value, a :: ann)
  185. | Const (IntVal value, ann) ->
  186. Const (IntVal value, a :: ann)
  187. | Const (FloatVal value, ann) ->
  188. Const (FloatVal value, a :: ann)
  189. | ArrayConst (value, ann) ->
  190. ArrayConst (value, a :: ann)
  191. | Param (ctype, name, ann) ->
  192. Param (ctype, name, a :: ann)
  193. | Dim (name, ann) ->
  194. Dim (name, a :: ann)
  195. | _ -> raise InvalidNode
  196. let rec annof = function
  197. | Program (_, ann)
  198. | Param (_, _, ann)
  199. | Dim (_, ann)
  200. | FunDec (_, _, _, ann)
  201. | FunDef (_, _, _, _, _, ann)
  202. | GlobalDec (_, _, ann)
  203. | GlobalDef (_, _, _, _, ann)
  204. | VarDec (_, _, _, ann)
  205. | Assign (_, _, _, ann)
  206. | VarLet (_, _, _, ann)
  207. | Return (_, ann)
  208. | If (_, _, ann)
  209. | IfElse (_, _, _, ann)
  210. | While (_, _, ann)
  211. | DoWhile (_, _, ann)
  212. | For (_, _, _, _, _, ann)
  213. | Allocate (_, _, ann)
  214. | Const (BoolVal _, ann)
  215. | Const (IntVal _, ann)
  216. | Const (FloatVal _, ann)
  217. | ArrayConst (_, ann)
  218. | Var (_, _, ann)
  219. | Monop (_, _, ann)
  220. | Binop (_, _, _, ann)
  221. | Cond (_, _, _, ann)
  222. | TypeCast (_, _, ann)
  223. | VarUse (_, _, ann)
  224. | FunUse (_, _, ann)
  225. | FunCall (_, _, ann) -> ann
  226. | ArrayInit (value, _)
  227. | Expr value
  228. | Arg value -> annof value
  229. | _ -> raise InvalidNode
  230. let locof node =
  231. let rec trav = function
  232. | [] -> noloc
  233. | Loc loc :: _ -> loc
  234. | _ :: tl -> trav tl
  235. in trav (annof node)
  236. let depthof node =
  237. let rec trav = function
  238. | [] ->
  239. prerr_string "cannot get depth for: ";
  240. prt_node node;
  241. raise InvalidNode
  242. | Depth depth :: _ -> depth
  243. | _ :: tl -> trav tl
  244. in trav (annof node)
  245. let indexof node =
  246. let rec trav = function
  247. | [] ->
  248. prerr_string "cannot get index for: ";
  249. prt_node node;
  250. raise InvalidNode
  251. | Index index :: _ -> index
  252. | _ :: tl -> trav tl
  253. in trav (annof node)
  254. let typeof = function
  255. (* Some nodes have their type as property *)
  256. | VarDec (ctype, _, _, _)
  257. | Param (ctype, _, _)
  258. | FunDec (ctype, _, _, _)
  259. | FunDef (_, ctype, _, _, _, _)
  260. | GlobalDec (ctype, _, _)
  261. | GlobalDef (_, ctype, _, _, _)
  262. | TypeCast (ctype, _, _)
  263. -> ctype
  264. (* Dim nodes are always type Int, and are copied by context analysis before
  265. * they are annotated with Type Int, so this match is necessary *)
  266. | Dim _ -> Int
  267. (* Other nodes must be annotated during typechecking *)
  268. | node ->
  269. let rec trav = function
  270. | [] ->
  271. prerr_string "cannot get type for: ";
  272. prt_node node;
  273. raise InvalidNode
  274. | Type t :: _ -> t
  275. | _ :: tl -> trav tl
  276. in trav (annof node)
  277. let labelof node =
  278. let rec trav = function
  279. | [] ->
  280. prerr_string "cannot get label for: ";
  281. prt_node node;
  282. raise InvalidNode
  283. | LabelName label :: _ -> label
  284. | _ :: tl -> trav tl
  285. in trav (annof node)
  286. let const_type = function
  287. | BoolVal _ -> Bool
  288. | IntVal _ -> Int
  289. | FloatVal _ -> Float
  290. (*
  291. let get_line str n =
  292. let rec find_start from = function
  293. | n when n < 1 -> raise (Invalid_argument "n")
  294. | 1 -> from
  295. | n -> find_start ((String.index_from str from '\n') + 1) (n - 1)
  296. in
  297. let linestart = find_start 0 n in
  298. let len = String.length str in
  299. let lineend =
  300. try String.index_from str linestart '\n'
  301. with Not_found -> len
  302. in
  303. String.sub str linestart (lineend - linestart)
  304. *)
  305. let count_tabs str upto =
  306. let rec count n = function
  307. | 0 -> n
  308. | i -> count (if String.get str (i - 1) = '\t' then n + 1 else n) (i - 1)
  309. in count 0 upto
  310. let tabwidth = 4
  311. let retab str = global_replace (regexp "\t") (repeat " " tabwidth) str
  312. let indent n = repeat (repeat " " (tabwidth - 1)) n
  313. let prerr_loc (fname, ystart, yend, xstart, xend) =
  314. let file = open_in fname in
  315. (* skip lines until the first matched line *)
  316. for i = 1 to ystart - 1 do let _ = input_line file in () done;
  317. (* for each line in `loc`, print the source line with an underline *)
  318. for l = ystart to yend do
  319. let line = input_line file in
  320. let linewidth = String.length line in
  321. let left = if l = ystart then xstart else 1 in
  322. let right = if l = yend then xend else linewidth in
  323. if linewidth > 0 then begin
  324. prerr_endline (retab line);
  325. prerr_string (indent (count_tabs line right));
  326. for i = 1 to left - 1 do prerr_char ' ' done;
  327. for i = left to right do prerr_char '^' done;
  328. prerr_endline "";
  329. end
  330. done;
  331. ()
  332. let prerr_loc_msg loc msg =
  333. if Globals.args.verbose >= 1 then begin
  334. let (fname, ystart, yend, xstart, xend) = loc in
  335. if loc != noloc then begin
  336. let line_s = if yend != ystart
  337. then sprintf "lines %d-%d" ystart yend
  338. else sprintf "line %d" ystart
  339. in
  340. let char_s = if xend != xstart || yend != ystart
  341. then sprintf "characters %d-%d" xstart xend
  342. else sprintf "character %d" xstart
  343. in
  344. eprintf "File \"%s\", %s, %s:\n" fname line_s char_s;
  345. end;
  346. eprintf "%s\n" msg;
  347. if Globals.args.verbose >= 1 && loc != noloc then
  348. try prerr_loc loc
  349. with Sys_error _ -> ()
  350. end;
  351. ()
  352. let block_body = function
  353. | Block nodes -> nodes
  354. | _ -> raise InvalidNode
  355. let basetypeof node = match typeof node with
  356. | ArrayDims (ctype, _)
  357. | Array ctype
  358. | ctype -> ctype
  359. let nameof = function
  360. | GlobalDec (_, name, _)
  361. | GlobalDef (_, _, name, _, _)
  362. | FunDec (_, name, _, _)
  363. | FunDef (_, _, name, _, _, _)
  364. | VarDec (_, name, _, _)
  365. | Param (_, name, _)
  366. | Dim (name, _) -> name
  367. | _ -> raise InvalidNode
  368. let optmap f = function
  369. | None -> None
  370. | Some lst -> Some (List.map f lst)
  371. let optmapl f = function
  372. | None -> []
  373. | Some lst -> List.map f lst
  374. let mapi f lst =
  375. let rec trav i = function
  376. | [] -> []
  377. | hd :: tl -> f i hd :: (trav (i + 1) tl)
  378. in trav 0 lst
  379. (** Constants that are *)
  380. let immediate_consts = [
  381. BoolVal true;
  382. BoolVal false;
  383. IntVal (-1);
  384. IntVal 0;
  385. IntVal 1;
  386. FloatVal 0.0;
  387. FloatVal 1.0;
  388. ]
  389. let is_immediate_const const =
  390. if Globals.args.optimize then List.mem const immediate_consts else false
  391. let is_array node = match typeof node with
  392. | ArrayDims _ | Array _ -> true
  393. | _ -> false
  394. let node_error node msg =
  395. prerr_loc_msg (locof node) ("Error: " ^ msg)
  396. let node_warning node msg =
  397. prerr_loc_msg (locof node) ("Warning: " ^ msg)