util.ml 13 KB

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