context_analysis.ml 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. open Printf
  2. open Ast
  3. open Util
  4. module StrMap = Map.Make (String)
  5. let analyse_context node =
  6. let scope = ref StrMap.empty in
  7. let add_to_scope name decl depth desc =
  8. if StrMap.mem name !scope then(
  9. raise (NodeError (!decl, sprintf "cannot redeclare %s \"%s\"" desc name))
  10. ) else
  11. scope := StrMap.add name (decl, depth) !scope
  12. in
  13. let rec analyse depth = function
  14. (* Add node reference for this varname to vars map *)
  15. | VarDec (ctype, name, init, loc) as node ->
  16. let node = match init with
  17. | Some value ->
  18. let value = analyse depth value in
  19. VarDec (ctype, name, Some value, loc)
  20. | None -> node
  21. in
  22. add_to_scope name (ref node) depth "variable";
  23. node
  24. (* For a variable, look for its declaration in the current scope and
  25. * save a reference with the relative nesting depth *)
  26. | Var (name, _) as node ->
  27. if StrMap.mem name !scope then
  28. let (decl, decl_depth) = StrMap.find name !scope in
  29. VarUse (node, decl, depth - decl_depth)
  30. else
  31. raise (NodeError (node, (sprintf "undefined variable \"%s\"" name)))
  32. (*
  33. (* Increase nesting level when entering function *)
  34. | FunDef (export, ret_type, name, params, body, loc) as node ->
  35. let vars = StrMap.add name (ref node) vars in
  36. let inctrav vars = function
  37. | [] -> []
  38. | h :: t -> analyse vars h :: (inctrav vars
  39. in
  40. let body = inc_trav body
  41. let body = List.map (analyse vars) body in
  42. FunDef (export, ret_type, name, params, body, loc) as node ->
  43. *)
  44. | node -> transform_children (analyse depth) node
  45. in
  46. analyse 0 node
  47. let rec phase input =
  48. prerr_endline "- Context analysis";
  49. match input with
  50. | Ast (node, args) ->
  51. Ast (analyse_context node, args)
  52. | _ -> raise (InvalidInput "context analysis")