gencommon.ml 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. (*
  2. The Haxe Compiler
  3. Copyright (C) 2005-2019 Haxe Foundation
  4. This program is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU General Public License
  6. as published by the Free Software Foundation; either version 2
  7. of the License, or (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  15. *)
  16. (*
  17. Gen Common API
  18. This is the key module for generation of Java and C# sources
  19. In order for both modules to share as much code as possible, some
  20. rules were devised:
  21. - every feature has its own submodule, and may contain the following methods:
  22. - configure
  23. sets all the configuration variables for the module to run. If a module has this method,
  24. it *should* be called once before running any filter
  25. - run_filter ->
  26. runs the filter immediately on the context
  27. - add_filter ->
  28. adds the filter to an expr->expr list. Most filter modules will provide this option so the filter
  29. function can only run once.
  30. - most submodules will have side-effects so the order of operations will matter.
  31. When running configure / add_filter this might be taken care of with the rule-based dispatch system working
  32. underneath, but still there might be some incompatibilities. There will be an effort to document it.
  33. The modules can hint on the order by suffixing their functions with _first or _last.
  34. - any of those methods might have different parameters, that configure how the filter will run.
  35. For example, a simple filter that maps switch() expressions to if () .. else if... might receive
  36. a function that filters what content should be mapped
  37. - Other targets can use those filters on their own code. In order to do that,
  38. a simple configuration step is needed: you need to initialize a generator_ctx type with
  39. Gencommon.new_gen (context:Common.context)
  40. with a generator_ctx context you will be able to add filters to your code, and execute them with
  41. Gencommon.run_filters (gen_context:Gencommon.generator_ctx)
  42. After running the filters, you can run your own generator normally.
  43. (* , or you can run
  44. Gencommon.generate_modules (gen_context:Gencommon.generator_ctx) (extension:string) (module_gen:module_type list->bool)
  45. where module_gen will take a whole module (can be *)
  46. *)
  47. open Unix
  48. open Ast
  49. open Type
  50. open Common
  51. open Globals
  52. open Option
  53. open Printf
  54. open ExtString
  55. open Overloads
  56. (* ******************************************* *)
  57. (* common helpers *)
  58. (* ******************************************* *)
  59. let rec like_float t =
  60. match follow t with
  61. | TAbstract ({ a_path = ([], "Float") }, [])
  62. | TAbstract ({ a_path = ([], "Int") }, []) ->
  63. true
  64. | TAbstract ({ a_path = (["cs"], "Pointer") }, _) ->
  65. false
  66. | TAbstract (a, _) ->
  67. List.exists like_float a.a_from || List.exists like_float a.a_to
  68. | _ ->
  69. false
  70. let rec like_int t =
  71. match follow t with
  72. | TAbstract ({ a_path = ([], "Int") }, []) ->
  73. true
  74. | TAbstract ({ a_path = (["cs"], "Pointer") }, _) ->
  75. false
  76. | TAbstract (a, _) ->
  77. List.exists like_int a.a_from || List.exists like_int a.a_to
  78. | _ ->
  79. false
  80. let rec like_i64 t =
  81. match follow t with
  82. | TAbstract ({ a_path = (["cs"], ("Int64" | "UInt64")) }, [])
  83. | TAbstract ({ a_path = (["java"], "Int64") }, [])
  84. | TAbstract ({ a_path = (["haxe"], "Int64") }, []) ->
  85. true
  86. | TAbstract (a, _) ->
  87. List.exists like_i64 a.a_from || List.exists like_i64 a.a_to
  88. | _ ->
  89. false
  90. let follow_once t =
  91. match t with
  92. | TMono r ->
  93. (match r.tm_type with
  94. | Some t -> t
  95. | _ -> t_dynamic) (* avoid infinite loop / should be the same in this context *)
  96. | TLazy f ->
  97. lazy_type f
  98. | TType (t,tl) ->
  99. apply_typedef t tl
  100. | TAbstract({a_path = [],"Null"},[t]) ->
  101. t
  102. | _ ->
  103. t
  104. let t_empty = mk_anon (ref Closed)
  105. let alloc_var n t = Type.alloc_var VGenerated n t null_pos
  106. let mk_local = Texpr.Builder.make_local
  107. (* the undefined is a special var that works like null, but can have special meaning *)
  108. let undefined =
  109. (fun pos -> mk (TIdent "__undefined__") t_dynamic pos)
  110. let path_of_md_def md_def =
  111. match md_def.m_types with
  112. | [TClassDecl c] -> c.cl_path
  113. | _ -> md_def.m_path
  114. let debug_type t = (s_type (print_context())) t
  115. let debug_expr = s_expr_ast true "" debug_type
  116. let debug_mode = ref false
  117. let trace s = if !debug_mode then print_endline s else ()
  118. let timer name = if !debug_mode then Timer.timer name else fun () -> ()
  119. let is_string t =
  120. match follow t with
  121. | TInst({ cl_path = ([], "String") }, []) -> true
  122. | _ -> false
  123. let anon_class t =
  124. match follow t with
  125. | TAnon anon ->
  126. (match !(anon.a_status) with
  127. | Statics cl -> Some (TClassDecl cl)
  128. | EnumStatics e -> Some (TEnumDecl e)
  129. | AbstractStatics a -> Some (TAbstractDecl a)
  130. | _ -> None)
  131. | _ -> None
  132. let rec t_to_md t = match t with
  133. | TInst (cl,_) -> TClassDecl cl
  134. | TEnum (e,_) -> TEnumDecl e
  135. | TType (t,_) -> TTypeDecl t
  136. | TAbstract (a,_) -> TAbstractDecl a
  137. | TAnon anon ->
  138. (match !(anon.a_status) with
  139. | EnumStatics e -> TEnumDecl e
  140. | Statics cl -> TClassDecl cl
  141. | AbstractStatics a -> TAbstractDecl a
  142. | _ -> die "" __LOC__)
  143. | TLazy f -> t_to_md (lazy_type f)
  144. | TMono r -> (match r.tm_type with | Some t -> t_to_md t | None -> die "" __LOC__)
  145. | _ -> die "" __LOC__
  146. let get_cl mt = match mt with TClassDecl cl -> cl | _ -> failwith (Printf.sprintf "Unexpected module type (class expected) for %s: %s" (s_type_path (t_path mt)) (s_module_type_kind mt))
  147. let get_abstract mt = match mt with TAbstractDecl a -> a | _ -> failwith (Printf.sprintf "Unexpected module type (abstract expected) for %s: %s" (s_type_path (t_path mt)) (s_module_type_kind mt))
  148. let get_fun t =
  149. match follow t with
  150. | TFun (args, ret) -> args, ret
  151. | t -> (trace (debug_type t)); die "" __LOC__
  152. let mk_cast t e = Type.mk_cast e t e.epos
  153. (** TODO: when adding new AST, make a new cast type for those fast casts. For now, we're using this hack
  154. * of using null_class to tell a fast cast from a normal one. Also note that this only works since both
  155. * C# and Java do not use the second part of TCast for anything *)
  156. let mk_castfast t e = { e with eexpr = TCast(e, Some (TClassDecl null_class)); etype = t }
  157. let mk_static_field_access_infer cl field pos params =
  158. try
  159. let e_type = Texpr.Builder.make_static_this cl pos in
  160. let cf = PMap.find field cl.cl_statics in
  161. let t = if params = [] then cf.cf_type else apply_params cf.cf_params params cf.cf_type in
  162. mk (TField(e_type, FStatic(cl, cf))) t pos
  163. with Not_found ->
  164. failwith ("Cannot find field " ^ field ^ " in class " ^ (s_type_path cl.cl_path))
  165. let mk_static_field_access cl field fieldt pos =
  166. { (mk_static_field_access_infer cl field pos []) with etype = fieldt }
  167. (* stolen from Hugh's sources ;-) *)
  168. (* this used to be a class, but there was something in there that crashed ocaml native compiler in windows *)
  169. module SourceWriter =
  170. struct
  171. type source_writer =
  172. {
  173. sw_buf : Buffer.t;
  174. mutable sw_has_content : bool;
  175. mutable sw_indent : string;
  176. mutable sw_indents : string list;
  177. }
  178. let new_source_writer () =
  179. {
  180. sw_buf = Buffer.create 0;
  181. sw_has_content = false;
  182. sw_indent = "";
  183. sw_indents = [];
  184. }
  185. let add_writer w_write w_read = Buffer.add_buffer w_read.sw_buf w_write.sw_buf
  186. let contents w = Buffer.contents w.sw_buf
  187. let len w = Buffer.length w.sw_buf
  188. let write w x =
  189. (if not w.sw_has_content then begin w.sw_has_content <- true; Buffer.add_string w.sw_buf w.sw_indent; Buffer.add_string w.sw_buf x; end else Buffer.add_string w.sw_buf x);
  190. let len = (String.length x)-1 in
  191. if len >= 0 && String.get x len = '\n' then begin w.sw_has_content <- false end else w.sw_has_content <- true
  192. let push_indent w = w.sw_indents <- "\t"::w.sw_indents; w.sw_indent <- String.concat "" w.sw_indents
  193. let pop_indent w =
  194. match w.sw_indents with
  195. | h::tail -> w.sw_indents <- tail; w.sw_indent <- String.concat "" w.sw_indents
  196. | [] -> w.sw_indent <- "/*?*/"
  197. let newline w = write w "\n"
  198. let begin_block w = (if w.sw_has_content then newline w); write w "{"; push_indent w; newline w
  199. let end_block w = pop_indent w; (if w.sw_has_content then newline w); write w "}"; newline w
  200. let print w =
  201. (if not w.sw_has_content then begin w.sw_has_content <- true; Buffer.add_string w.sw_buf w.sw_indent end);
  202. bprintf w.sw_buf;
  203. end;;
  204. (* rule_dispatcher's priority *)
  205. type priority =
  206. | PFirst
  207. | PLast
  208. | PZero
  209. | PCustom of float
  210. exception DuplicateName of string
  211. exception NoRulesApplied
  212. let indent = ref []
  213. (* the rule dispatcher is the primary way to deal with distributed "plugins" *)
  214. (* we will define rules that will form a distributed / extensible match system *)
  215. class ['tp, 'ret] rule_dispatcher name =
  216. object(self)
  217. val tbl = Hashtbl.create 16
  218. val mutable keys = []
  219. val names = Hashtbl.create 16
  220. method add (name : string) (* name helps debugging *) (priority : priority) (rule : 'tp->'ret option) =
  221. let p = match priority with
  222. | PFirst -> infinity
  223. | PLast -> neg_infinity
  224. | PZero -> 0.0
  225. | PCustom i -> i
  226. in
  227. let q = if not( Hashtbl.mem tbl p ) then begin
  228. let q = Stack.create() in
  229. Hashtbl.add tbl p q;
  230. keys <- p :: keys;
  231. keys <- List.sort (fun x y -> - (compare x y)) keys;
  232. q
  233. end else Hashtbl.find tbl p in
  234. (if Hashtbl.mem names name then raise (DuplicateName(name)));
  235. Hashtbl.add names name q;
  236. Stack.push (name, rule) q
  237. method describe =
  238. Hashtbl.iter (fun s _ -> (trace s)) names;
  239. method run_f tp = get (self#run tp)
  240. method run_from (priority:float) (tp:'tp) : 'ret option =
  241. let ok = ref false in
  242. let ret = ref None in
  243. indent := "\t" :: !indent;
  244. (try begin
  245. List.iter (fun key ->
  246. if key < priority then begin
  247. let q = Hashtbl.find tbl key in
  248. Stack.iter (fun (n, rule) ->
  249. let t = if !debug_mode then Timer.timer [("rule dispatcher rule: " ^ n)] else fun () -> () in
  250. let r = rule(tp) in
  251. t();
  252. if is_some r then begin ret := r; raise Exit end
  253. ) q
  254. end
  255. ) keys
  256. end with Exit -> ok := true);
  257. (match !indent with
  258. | [] -> ()
  259. | h::t -> indent := t);
  260. (if not (!ok) then raise NoRulesApplied);
  261. !ret
  262. method run (tp:'tp) : 'ret option =
  263. self#run_from infinity tp
  264. end;;
  265. (* this is a special case where tp = tret and you stack their output as the next's input *)
  266. class ['tp] rule_map_dispatcher name = object(self)
  267. val tbl = Hashtbl.create 16
  268. val mutable keys = []
  269. val names = Hashtbl.create 16
  270. method add (name : string) (* name helps debugging *) (priority : priority) (rule : 'tp->'tp) =
  271. let p = match priority with
  272. | PFirst -> infinity
  273. | PLast -> neg_infinity
  274. | PZero -> 0.0
  275. | PCustom i -> i
  276. in
  277. let q = if not (Hashtbl.mem tbl p) then begin
  278. let q = Stack.create() in
  279. Hashtbl.add tbl p q;
  280. keys <- p :: keys;
  281. keys <- List.sort (fun x y -> - (compare x y)) keys;
  282. q
  283. end else Hashtbl.find tbl p in
  284. if Hashtbl.mem names name then raise (DuplicateName name);
  285. Hashtbl.add names name q;
  286. Stack.push (name, rule) q
  287. method describe =
  288. Hashtbl.iter (fun s _ -> (trace s)) names;
  289. method run (tp:'tp) : 'tp =
  290. self#run_from infinity tp
  291. method run_from (priority:float) (tp:'tp) : 'tp =
  292. let cur = ref tp in
  293. List.iter (fun key ->
  294. if key < priority then begin
  295. let q = Hashtbl.find tbl key in
  296. Stack.iter (fun (n, rule) ->
  297. trace ("running rule " ^ n);
  298. let t = if !debug_mode then Timer.timer [("rule map dispatcher rule: " ^ n)] else fun () -> () in
  299. cur := rule !cur;
  300. t();
  301. ) q
  302. end
  303. ) keys;
  304. !cur
  305. end;;
  306. type generator_ctx =
  307. {
  308. (* these are the basic context fields. If another target is using this context, *)
  309. (* this is all you need to care about *)
  310. gcon : Common.context;
  311. gentry_point : (string * tclass * texpr) option;
  312. gclasses : gen_classes;
  313. gtools : gen_tools;
  314. gwarning : Warning.warning -> string -> pos -> unit;
  315. (*
  316. module filters run before module filters and they should generate valid haxe syntax as a result.
  317. Module filters shouldn't go through the expressions as it adds an unnecessary burden to the GC,
  318. and it can all be done in a single step with gexpr_filters and proper priority selection.
  319. As a convention, Module filters should end their name with Modf, so they aren't mistaken with expression filters
  320. *)
  321. gmodule_filters : (module_type) rule_map_dispatcher;
  322. (*
  323. expression filters are the most common filters to be applied.
  324. They should also generate only valid haxe expressions, so e.g. calls to non-existant methods
  325. should be avoided, although there are some ways around them (like gspecial_methods)
  326. *)
  327. gexpr_filters : (texpr) rule_map_dispatcher;
  328. (*
  329. syntax filters are also expression filters but they no longer require
  330. that the resulting expressions be valid haxe expressions.
  331. They then have no guarantee that either the input expressions or the output one follow the same
  332. rules as normal haxe code.
  333. *)
  334. gsyntax_filters : (texpr) rule_map_dispatcher;
  335. (* these are more advanced features, but they would require a rewrite of targets *)
  336. (* they are just helpers to ditribute functions like "follow" or "type to string" *)
  337. (* so adding a module will already take care of correctly following a certain type of *)
  338. (* variable, for example *)
  339. (* follows the type through typedefs, lazy typing, etc. *)
  340. (* it's the place to put specific rules to handle typedefs, like *)
  341. (* other basic types like UInt *)
  342. gfollow : (t, t) rule_dispatcher;
  343. gtypes : (path, module_type) Hashtbl.t;
  344. mutable gtypes_list : module_type list;
  345. mutable gmodules : Type.module_def list;
  346. (* cast detection helpers / settings *)
  347. (* this is a cache for all field access types *)
  348. greal_field_types : (path * string, (tclass_field (* does the cf exist *) * t (*cf's type in relation to current class type params *) * t * tclass (* declared class *) ) option) Hashtbl.t;
  349. (* this function allows any code to handle casts as if it were inside the cast_detect module *)
  350. mutable ghandle_cast : t->t->texpr->texpr;
  351. (* when an unsafe cast is made, we can warn the user *)
  352. mutable gon_unsafe_cast : t->t->pos->unit;
  353. (* does this type needs to be boxed? Normally always false, unless special type handling must be made *)
  354. mutable gneeds_box : t->bool;
  355. (* does this 'special type' needs cast to this other type? *)
  356. (* this is here so we can implement custom behavior for "opaque" typedefs *)
  357. mutable gspecial_needs_cast : t->t->bool;
  358. (* sometimes we may want to support unrelated conversions on cast detection *)
  359. (* for example, haxe.lang.Null<T> -> T on C# *)
  360. (* every time an unrelated conversion is found, each to/from path is searched on this hashtbl *)
  361. (* if found, the function will be executed with from_type, to_type. If returns true, it means that *)
  362. (* it is a supported conversion, and the unsafe cast routine changes to a simple cast *)
  363. gsupported_conversions : (path, t->t->bool) Hashtbl.t;
  364. (* API for filters *)
  365. (* add type can be called at any time, and will add a new module_def that may or may not be filtered *)
  366. (* module_type -> should_filter *)
  367. mutable gadd_type : module_type -> bool -> unit;
  368. (* during expr filters, add_to_module will be available so module_types can be added to current module_def. we must pass the priority argument so the filters can be resumed *)
  369. mutable gadd_to_module : module_type -> float -> unit;
  370. (* during expr filters, shows the current class path *)
  371. mutable gcurrent_path : path;
  372. (* current class *)
  373. mutable gcurrent_class : tclass option;
  374. (* current class field, if any *)
  375. mutable gcurrent_classfield : tclass_field option;
  376. (* events *)
  377. (* after module filters ended *)
  378. mutable gafter_mod_filters_ended : (unit -> unit) list;
  379. (* after expression filters ended *)
  380. mutable gafter_expr_filters_ended : (unit -> unit) list;
  381. (* after all filters are run *)
  382. mutable gafter_filters_ended : (unit -> unit) list;
  383. mutable gbase_class_fields : (string, tclass_field) PMap.t;
  384. (* real type is the type as it is read by the target. *)
  385. (* This function is here because most targets don't have *)
  386. (* a 1:1 translation between haxe types and its native types *)
  387. (* But types aren't changed to this representation as we might lose *)
  388. (* some valuable type information in the process *)
  389. mutable greal_type : t -> t;
  390. (*
  391. the same as greal_type but for type parameters.
  392. *)
  393. mutable greal_type_param : module_type -> tparams -> tparams;
  394. (*
  395. is the type a value type?
  396. This may be used in some optimizations where reference types and value types
  397. are handled differently. At first the default is very good to use, and if tweaks are needed,
  398. it's best to be done by adding @:struct meta to the value types
  399. *
  400. mutable gis_value_type : t -> bool;*)
  401. (* misc configuration *)
  402. (*
  403. Should the target allow type parameter dynamic conversion,
  404. or should we add a cast to those cases as well?
  405. *)
  406. mutable gallow_tp_dynamic_conversion : bool;
  407. (* internal apis *)
  408. (* param_func_call : used by RealTypeParams and CastDetection *)
  409. mutable gparam_func_call : texpr->texpr->tparams->texpr list->texpr;
  410. (* does it already have a type parameter cast handler? This is used by CastDetect to know if it should handle type parameter casts *)
  411. mutable ghas_tparam_cast_handler : bool;
  412. (* type parameter casts - special cases *)
  413. (* function cast_from, cast_to -> texpr *)
  414. gtparam_cast : (path, (texpr->t->texpr)) Hashtbl.t;
  415. (*
  416. special vars are used for adding special behavior to
  417. *)
  418. gspecial_vars : (string, bool) Hashtbl.t;
  419. }
  420. and gen_classes =
  421. {
  422. cl_reflect : tclass;
  423. cl_type : tclass;
  424. cl_dyn : tclass;
  425. mutable nativearray_len : texpr -> pos -> texpr;
  426. mutable nativearray_type : Type.t -> Type.t;
  427. mutable nativearray : Type.t -> Type.t;
  428. }
  429. (* add here all reflection transformation additions *)
  430. and gen_tools =
  431. {
  432. (* Reflect.fields(). The bool is if we are iterating in a read-only manner. If it is read-only we might not need to allocate a new array *)
  433. r_fields : bool->texpr->texpr;
  434. (* (first argument = return type. should be void in most cases) Reflect.setField(obj, field, val) *)
  435. r_set_field : t->texpr->texpr->texpr->texpr;
  436. (* Reflect.field. bool indicates if is safe (no error throwing) or unsafe; t is the expected return type true = safe *)
  437. r_field : bool->t->texpr->texpr->texpr;
  438. (*
  439. return an expression that creates an unitialized instance of a class, used for the generic cast helper method.
  440. *)
  441. mutable r_create_empty : tclass->tparams->pos->texpr;
  442. }
  443. (**
  444. Function that receives a desired name and makes it "internal", doing the best to ensure that it will not be called from outside.
  445. To avoid name clashes between internal names, user must specify two strings: a "namespace" and the name itself
  446. *)
  447. let mk_internal_name ns name = Printf.sprintf "__%s_%s" ns name
  448. let mk_temp, reset_temps =
  449. let tmp_count = ref 0 in
  450. (fun name t ->
  451. incr tmp_count;
  452. let name = mk_internal_name "temp" (name ^ (string_of_int !tmp_count)) in
  453. alloc_var name t
  454. ),
  455. (fun () -> tmp_count := 0)
  456. let new_ctx con =
  457. let types = Hashtbl.create (List.length con.types) in
  458. List.iter (fun mt ->
  459. match mt with
  460. | TClassDecl cl -> Hashtbl.add types cl.cl_path mt
  461. | TEnumDecl e -> Hashtbl.add types e.e_path mt
  462. | TTypeDecl t -> Hashtbl.add types t.t_path mt
  463. | TAbstractDecl a ->
  464. (* There are some cases where both an abstract and a class
  465. have the same name (e.g. java.lang.Double/Integer/etc)
  466. in this case we generally want the class to have priority *)
  467. if not (Hashtbl.mem types a.a_path) then
  468. Hashtbl.add types a.a_path mt
  469. ) con.types;
  470. let get_type path =
  471. List.find (fun md -> (t_path md) = path) con.types
  472. in
  473. let cl_dyn = match get_type ([], "Dynamic") with
  474. | TClassDecl c -> c
  475. | TAbstractDecl a ->
  476. mk_class a.a_module ([], "Dynamic") a.a_pos null_pos
  477. | _ -> die "" __LOC__
  478. in
  479. let rec gen = {
  480. gcon = con;
  481. gwarning = (fun w msg p ->
  482. let options = Option.map_default (fun c -> Warning.from_meta c.cl_meta) [] gen.gcurrent_class in
  483. let options = options @ Option.map_default (fun cf -> Warning.from_meta cf.cf_meta) [] gen.gcurrent_classfield in
  484. con.warning w options msg p
  485. );
  486. gentry_point = get_entry_point con;
  487. gclasses = {
  488. cl_reflect = get_cl (get_type ([], "Reflect"));
  489. cl_type = get_cl (get_type ([], "Type"));
  490. cl_dyn = cl_dyn;
  491. nativearray = (fun _ -> die "" __LOC__);
  492. nativearray_type = (fun _ -> die "" __LOC__);
  493. nativearray_len = (fun _ -> die "" __LOC__);
  494. };
  495. gtools = {
  496. r_fields = (fun is_used_only_by_iteration expr ->
  497. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "fields" expr.epos [] in
  498. { eexpr = TCall(fieldcall, [expr]); etype = gen.gcon.basic.tarray gen.gcon.basic.tstring; epos = expr.epos }
  499. );
  500. (* Reflect.setField(obj, field, val). t by now is ignored. FIXME : fix this implementation *)
  501. r_set_field = (fun t obj field v ->
  502. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "setField" v.epos [] in
  503. { eexpr = TCall(fieldcall, [obj; field; v]); etype = t_dynamic; epos = v.epos }
  504. );
  505. (* Reflect.field. bool indicates if is safe (no error throwing) or unsafe. true = safe *)
  506. r_field = (fun is_safe t obj field ->
  507. let fieldcall = mk_static_field_access_infer gen.gclasses.cl_reflect "field" obj.epos [] in
  508. (* FIXME: should we see if needs to cast? *)
  509. mk_cast t { eexpr = TCall(fieldcall, [obj; field]); etype = t_dynamic; epos = obj.epos }
  510. );
  511. r_create_empty = (fun _ _ pos -> gen.gcon.error "r_create_empty implementation is not provided" pos; die "" __LOC__);
  512. };
  513. gexpr_filters = new rule_map_dispatcher "gexpr_filters";
  514. gmodule_filters = new rule_map_dispatcher "gmodule_filters";
  515. gsyntax_filters = new rule_map_dispatcher "gsyntax_filters";
  516. gfollow = new rule_dispatcher "gfollow";
  517. gtypes = types;
  518. gtypes_list = con.types;
  519. gmodules = con.modules;
  520. greal_field_types = Hashtbl.create 0;
  521. ghandle_cast = (fun to_t from_t e -> mk_cast to_t e);
  522. gon_unsafe_cast = (fun t t2 pos -> (gen.gwarning WGenerator ("Type " ^ (debug_type t2) ^ " is being cast to the unrelated type " ^ (s_type (print_context()) t)) pos));
  523. gneeds_box = (fun t -> false);
  524. gspecial_needs_cast = (fun to_t from_t -> false);
  525. gsupported_conversions = Hashtbl.create 0;
  526. gadd_type = (fun md should_filter ->
  527. if should_filter then begin
  528. gen.gtypes_list <- md :: gen.gtypes_list;
  529. gen.gmodules <- { m_id = alloc_mid(); m_path = (t_path md); m_types = [md]; m_statics = None; m_extra = module_extra "" "" 0. MFake [] } :: gen.gmodules;
  530. Hashtbl.add gen.gtypes (t_path md) md;
  531. end else gen.gafter_filters_ended <- (fun () ->
  532. gen.gtypes_list <- md :: gen.gtypes_list;
  533. gen.gmodules <- { m_id = alloc_mid(); m_path = (t_path md); m_types = [md]; m_statics = None; m_extra = module_extra "" "" 0. MFake [] } :: gen.gmodules;
  534. Hashtbl.add gen.gtypes (t_path md) md;
  535. ) :: gen.gafter_filters_ended;
  536. );
  537. gadd_to_module = (fun md pr -> failwith "module added outside expr filters");
  538. gcurrent_path = ([],"");
  539. gcurrent_class = None;
  540. gcurrent_classfield = None;
  541. gafter_mod_filters_ended = [];
  542. gafter_expr_filters_ended = [];
  543. gafter_filters_ended = [];
  544. gbase_class_fields = PMap.empty;
  545. greal_type = (fun t -> t);
  546. greal_type_param = (fun _ t -> t);
  547. gallow_tp_dynamic_conversion = false;
  548. (* as a default, ignore the params *)
  549. gparam_func_call = (fun ecall efield params elist -> { ecall with eexpr = TCall(efield, elist) });
  550. ghas_tparam_cast_handler = false;
  551. gtparam_cast = Hashtbl.create 0;
  552. gspecial_vars = Hashtbl.create 0;
  553. } in
  554. gen
  555. let init_ctx gen =
  556. (* ultimately add a follow once handler as the last follow handler *)
  557. let follow_f = gen.gfollow#run in
  558. let follow t =
  559. match t with
  560. | TMono r ->
  561. (match r.tm_type with
  562. | Some t -> follow_f t
  563. | _ -> Some t)
  564. | TLazy f ->
  565. follow_f (lazy_type f)
  566. | TType (t,tl) ->
  567. follow_f (apply_typedef t tl)
  568. | TAbstract({a_path = [],"Null"},[t]) ->
  569. follow_f t
  570. | _ -> Some t
  571. in
  572. gen.gfollow#add "final" PLast follow
  573. let run_follow gen = gen.gfollow#run_f
  574. let reorder_modules gen =
  575. let modules = Hashtbl.create 20 in
  576. List.iter (fun md ->
  577. Hashtbl.add modules ( (t_infos md).mt_module ).m_path md
  578. ) gen.gtypes_list;
  579. gen.gmodules <- [];
  580. let processed = Hashtbl.create 20 in
  581. Hashtbl.iter (fun md_path md ->
  582. if not (Hashtbl.mem processed md_path) then begin
  583. Hashtbl.add processed md_path true;
  584. gen.gmodules <- { m_id = alloc_mid(); m_path = md_path; m_types = List.rev ( Hashtbl.find_all modules md_path ); m_statics = None; m_extra = (t_infos md).mt_module.m_extra } :: gen.gmodules
  585. end
  586. ) modules
  587. let run_filters_from gen t filters =
  588. match t with
  589. | TClassDecl c when not (FiltersCommon.is_removable_class c) ->
  590. trace (snd c.cl_path);
  591. gen.gcurrent_path <- c.cl_path;
  592. gen.gcurrent_class <- Some(c);
  593. gen.gcurrent_classfield <- None;
  594. let rec process_field f =
  595. reset_temps();
  596. gen.gcurrent_classfield <- Some(f);
  597. trace f.cf_name;
  598. (match f.cf_expr with
  599. | None -> ()
  600. | Some e ->
  601. f.cf_expr <- Some (List.fold_left (fun e f -> f e) e filters));
  602. List.iter process_field f.cf_overloads;
  603. in
  604. List.iter process_field c.cl_ordered_fields;
  605. List.iter process_field c.cl_ordered_statics;
  606. (match c.cl_constructor with
  607. | None -> ()
  608. | Some f -> process_field f);
  609. gen.gcurrent_classfield <- None;
  610. (match c.cl_init with
  611. | None -> ()
  612. | Some e ->
  613. c.cl_init <- Some (List.fold_left (fun e f -> f e) e filters));
  614. | TClassDecl _ | TEnumDecl _ | TTypeDecl _ | TAbstractDecl _ ->
  615. ()
  616. let run_filters gen =
  617. let last_error = gen.gcon.error_ext in
  618. let has_errors = ref false in
  619. gen.gcon.error_ext <- (fun err -> has_errors := true; last_error err);
  620. (* first of all, we have to make sure that the filters won't trigger a major Gc collection *)
  621. let t = Timer.timer ["gencommon_filters"] in
  622. (if Common.defined gen.gcon Define.GencommonDebug then debug_mode := true else debug_mode := false);
  623. let run_filters (filter : texpr rule_map_dispatcher) =
  624. let rec loop acc mds =
  625. match mds with
  626. | [] -> acc
  627. | md :: tl ->
  628. let filters = [ filter#run ] in
  629. let added_types = ref [] in
  630. gen.gadd_to_module <- (fun md_type priority ->
  631. gen.gtypes_list <- md_type :: gen.gtypes_list;
  632. added_types := (md_type, priority) :: !added_types
  633. );
  634. run_filters_from gen md filters;
  635. let added_types = List.map (fun (t,p) ->
  636. run_filters_from gen t [ fun e -> filter#run_from p e ];
  637. if Hashtbl.mem gen.gtypes (t_path t) then begin
  638. let rec loop i =
  639. let p = t_path t in
  640. let new_p = (fst p, snd p ^ "_" ^ (string_of_int i)) in
  641. if Hashtbl.mem gen.gtypes new_p then
  642. loop (i+1)
  643. else
  644. match t with
  645. | TClassDecl cl -> cl.cl_path <- new_p
  646. | TEnumDecl e -> e.e_path <- new_p
  647. | TTypeDecl _ | TAbstractDecl _ -> ()
  648. in
  649. loop 0
  650. end;
  651. Hashtbl.add gen.gtypes (t_path t) t;
  652. t
  653. ) !added_types in
  654. loop (added_types @ (md :: acc)) tl
  655. in
  656. List.rev (loop [] gen.gtypes_list)
  657. in
  658. let run_mod_filter (filter : module_type rule_map_dispatcher) =
  659. let last_add_to_module = gen.gadd_to_module in
  660. let added_types = ref [] in
  661. gen.gadd_to_module <- (fun md_type priority ->
  662. Hashtbl.add gen.gtypes (t_path md_type) md_type;
  663. added_types := (md_type, priority) :: !added_types
  664. );
  665. let rec loop processed not_processed =
  666. match not_processed with
  667. | hd :: tl ->
  668. (match hd with
  669. | TClassDecl c ->
  670. gen.gcurrent_class <- Some c
  671. | _ ->
  672. gen.gcurrent_class <- None);
  673. let new_hd = filter#run hd in
  674. let added_types_new = !added_types in
  675. added_types := [];
  676. let added_types = List.map (fun (t,p) -> filter#run_from p t) added_types_new in
  677. loop ( added_types @ (new_hd :: processed) ) tl
  678. | [] ->
  679. processed
  680. in
  681. let filtered = loop [] gen.gtypes_list in
  682. gen.gadd_to_module <- last_add_to_module;
  683. gen.gtypes_list <- List.rev (filtered)
  684. in
  685. run_mod_filter gen.gmodule_filters;
  686. List.iter (fun fn -> fn()) gen.gafter_mod_filters_ended;
  687. let last_add_to_module = gen.gadd_to_module in
  688. gen.gtypes_list <- run_filters gen.gexpr_filters;
  689. gen.gadd_to_module <- last_add_to_module;
  690. List.iter (fun fn -> fn()) gen.gafter_expr_filters_ended;
  691. gen.gtypes_list <- run_filters gen.gsyntax_filters;
  692. List.iter (fun fn -> fn()) gen.gafter_filters_ended;
  693. reorder_modules gen;
  694. t();
  695. if !has_errors then abort "Compilation aborted with errors" null_pos
  696. (* ******************************************* *)
  697. (* basic generation module that source code compilation implementations can use *)
  698. (* ******************************************* *)
  699. let write_file gen w source_dir path extension out_files =
  700. let t = timer ["write";"file"] in
  701. let s_path = source_dir ^ "/" ^ (snd path) ^ "." ^ (extension) in
  702. (* create the folders if they don't exist *)
  703. Path.mkdir_from_path s_path;
  704. let contents = SourceWriter.contents w in
  705. let should_write = if not (Common.defined gen.gcon Define.ReplaceFiles) && Sys.file_exists s_path then begin
  706. let in_file = open_in s_path in
  707. let old_contents = Std.input_all in_file in
  708. close_in in_file;
  709. contents <> old_contents
  710. end else true in
  711. if should_write then begin
  712. let f = open_out_bin s_path in
  713. output_string f contents;
  714. close_out f
  715. end;
  716. out_files := (gen.gcon.file_keys#get s_path) :: !out_files;
  717. t()
  718. let clean_files gen path excludes verbose =
  719. let rec iter_files pack dir path = try
  720. let file = Unix.readdir dir in
  721. if file <> "." && file <> ".." then begin
  722. let filepath = path ^ "/" ^ file in
  723. if (Unix.stat filepath).st_kind = S_DIR then
  724. let pack = pack @ [file] in
  725. iter_files (pack) (Unix.opendir filepath) filepath;
  726. try Unix.rmdir filepath with Unix.Unix_error (ENOTEMPTY,_,_) -> ();
  727. else if not (String.ends_with filepath ".meta") && not (List.mem (gen.gcon.file_keys#get filepath) excludes) then begin
  728. if verbose then print_endline ("Removing " ^ filepath);
  729. Sys.remove filepath
  730. end
  731. end;
  732. iter_files pack dir path
  733. with | End_of_file | Unix.Unix_error _ ->
  734. Unix.closedir dir
  735. in
  736. iter_files [] (Unix.opendir path) path
  737. let dump_descriptor gen name path_s module_s =
  738. let w = SourceWriter.new_source_writer () in
  739. (* dump called path *)
  740. SourceWriter.write w (Sys.getcwd());
  741. SourceWriter.newline w;
  742. (* dump all defines. deprecated *)
  743. SourceWriter.write w "begin defines";
  744. SourceWriter.newline w;
  745. PMap.iter (fun name _ ->
  746. SourceWriter.write w name;
  747. SourceWriter.newline w
  748. ) gen.gcon.defines.Define.values;
  749. SourceWriter.write w "end defines";
  750. SourceWriter.newline w;
  751. (* dump all defines with their values; keeping the old defines for compatibility *)
  752. SourceWriter.write w "begin defines_data";
  753. SourceWriter.newline w;
  754. PMap.iter (fun name v ->
  755. SourceWriter.write w name;
  756. SourceWriter.write w "=";
  757. SourceWriter.write w v;
  758. SourceWriter.newline w
  759. ) gen.gcon.defines.Define.values;
  760. SourceWriter.write w "end defines_data";
  761. SourceWriter.newline w;
  762. (* dump all generated types *)
  763. SourceWriter.write w "begin modules";
  764. SourceWriter.newline w;
  765. let main_paths = Hashtbl.create 0 in
  766. List.iter (fun md_def ->
  767. SourceWriter.write w "M ";
  768. SourceWriter.write w (path_s (path_of_md_def md_def));
  769. SourceWriter.newline w;
  770. List.iter (fun m ->
  771. match m with
  772. | TClassDecl cl when not (has_class_flag cl CExtern) ->
  773. SourceWriter.write w "C ";
  774. let s = module_s m in
  775. Hashtbl.add main_paths cl.cl_path s;
  776. SourceWriter.write w (s);
  777. SourceWriter.newline w
  778. | TEnumDecl e when not e.e_extern ->
  779. SourceWriter.write w "E ";
  780. SourceWriter.write w (module_s m);
  781. SourceWriter.newline w
  782. | _ -> () (* still no typedef or abstract is generated *)
  783. ) md_def.m_types
  784. ) gen.gmodules;
  785. SourceWriter.write w "end modules";
  786. SourceWriter.newline w;
  787. (* dump all resources *)
  788. (match gen.gentry_point with
  789. | Some (_,cl,_) ->
  790. SourceWriter.write w "begin main";
  791. SourceWriter.newline w;
  792. let path = cl.cl_path in
  793. (try
  794. SourceWriter.write w (Hashtbl.find main_paths path)
  795. with Not_found ->
  796. SourceWriter.write w (path_s path));
  797. SourceWriter.newline w;
  798. SourceWriter.write w "end main";
  799. SourceWriter.newline w
  800. | _ -> ());
  801. SourceWriter.write w "begin resources";
  802. SourceWriter.newline w;
  803. Hashtbl.iter (fun name _ ->
  804. SourceWriter.write w name;
  805. SourceWriter.newline w
  806. ) gen.gcon.resources;
  807. SourceWriter.write w "end resources";
  808. SourceWriter.newline w;
  809. SourceWriter.write w "begin libs";
  810. SourceWriter.newline w;
  811. let path file ext =
  812. if Sys.file_exists file then
  813. file
  814. else try Common.find_file gen.gcon file with
  815. | Not_found -> try Common.find_file gen.gcon (file ^ ext) with
  816. | Not_found ->
  817. file
  818. in
  819. if Common.platform gen.gcon Java then
  820. List.iter (fun java_lib ->
  821. if not (java_lib#has_flag NativeLibraries.FlagIsStd) && not (java_lib#has_flag NativeLibraries.FlagIsExtern) then begin
  822. SourceWriter.write w (path java_lib#get_file_path ".jar");
  823. SourceWriter.newline w;
  824. end
  825. ) gen.gcon.native_libs.java_libs
  826. else if Common.platform gen.gcon Cs then
  827. List.iter (fun net_lib ->
  828. if not (net_lib#has_flag NativeLibraries.FlagIsStd) && not (net_lib#has_flag NativeLibraries.FlagIsExtern) then begin
  829. SourceWriter.write w (path net_lib#get_name ".dll");
  830. SourceWriter.newline w;
  831. end
  832. ) gen.gcon.native_libs.net_libs;
  833. SourceWriter.write w "end libs";
  834. SourceWriter.newline w;
  835. let args = gen.gcon.c_args in
  836. if args <> [] then begin
  837. SourceWriter.write w "begin opts";
  838. SourceWriter.newline w;
  839. List.iter (fun opt -> SourceWriter.write w opt; SourceWriter.newline w) (List.rev args);
  840. SourceWriter.write w "end opts";
  841. SourceWriter.newline w;
  842. end;
  843. let contents = SourceWriter.contents w in
  844. let f = open_out (gen.gcon.file ^ "/" ^ name) in
  845. output_string f contents;
  846. close_out f
  847. (*
  848. various helper functions
  849. *)
  850. let mk_paren e =
  851. match e.eexpr with | TParenthesis _ -> e | _ -> { e with eexpr=TParenthesis(e) }
  852. (* private *)
  853. let get_real_fun gen t =
  854. match follow t with
  855. | TFun(args,t) -> TFun(List.map (fun (n,o,t) -> n,o,gen.greal_type t) args, gen.greal_type t)
  856. | _ -> t
  857. let mk_nativearray_decl gen t el pos =
  858. mk (TCall (mk (TIdent "__array__") t_dynamic pos, el)) (gen.gclasses.nativearray t) pos
  859. let get_boxed gen t =
  860. let get path =
  861. try type_of_module_type (Hashtbl.find gen.gtypes path)
  862. with Not_found -> t
  863. in
  864. match follow t with
  865. | TAbstract({ a_path = ([],"Bool") }, []) ->
  866. get (["java";"lang"], "Boolean")
  867. | TAbstract({ a_path = ([],"Float") }, []) ->
  868. get (["java";"lang"], "Double")
  869. | TAbstract({ a_path = ([],"Int") }, []) ->
  870. get (["java";"lang"], "Integer")
  871. | TAbstract({ a_path = (["java"],"Int8") }, []) ->
  872. get (["java";"lang"], "Byte")
  873. | TAbstract({ a_path = (["java"],"Int16") }, []) ->
  874. get (["java";"lang"], "Short")
  875. | TAbstract({ a_path = (["java"],"Char16") }, []) ->
  876. get (["java";"lang"], "Character")
  877. | TAbstract({ a_path = ([],"Single") }, []) ->
  878. get (["java";"lang"], "Float")
  879. | TAbstract({ a_path = (["java"],"Int64") }, [])
  880. | TAbstract({ a_path = (["haxe"],"Int64") }, []) ->
  881. get (["java";"lang"], "Long")
  882. | _ -> t
  883. (**
  884. Wraps rest arguments into a native array.
  885. E.g. transforms params from `callee(param, rest1, rest2, ..., restN)` into
  886. `callee(param, untyped __array__(rest1, rest2, ..., restN))`
  887. *)
  888. let wrap_rest_args gen callee_type params p =
  889. match follow callee_type with
  890. | TFun(args, _) ->
  891. let rec loop args params =
  892. match args, params with
  893. (* last argument expects rest parameters *)
  894. | [(_,_,t)], params when ExtType.is_rest (follow t) ->
  895. (match params with
  896. (* In case of `...rest` just use `rest` *)
  897. | [{ eexpr = TUnop(Spread,Prefix,e) }] -> [e]
  898. (* In other cases: `untyped __array__(param1, param2, ...)` *)
  899. | _ ->
  900. match Abstract.follow_with_abstracts t with
  901. | TInst ({ cl_path = _,"NativeArray" }, [t1]) ->
  902. let t1 = if Common.defined gen.gcon Define.EraseGenerics then t_dynamic else get_boxed gen t1 in
  903. [mk_nativearray_decl gen t1 params (punion_el p params)]
  904. | _ ->
  905. die ~p "Unexpected rest arguments type" __LOC__
  906. )
  907. | a :: args, e :: params ->
  908. e :: loop args params
  909. | [], params ->
  910. params
  911. | _ :: _, [] ->
  912. []
  913. in
  914. loop args params
  915. | _ -> params
  916. let ensure_local com block name e =
  917. match e.eexpr with
  918. | TLocal _ -> e
  919. | _ ->
  920. let v = mk_temp name e.etype in
  921. block := (mk (TVar (v, Some e)) com.basic.tvoid e.epos) :: !block;
  922. mk_local v e.epos
  923. let follow_module follow_func md = match md with
  924. | TClassDecl _
  925. | TEnumDecl _
  926. | TAbstractDecl _ -> md
  927. | TTypeDecl tdecl -> match (follow_func (TType(tdecl, extract_param_types tdecl.t_params))) with
  928. | TInst(cl,_) -> TClassDecl cl
  929. | TEnum(e,_) -> TEnumDecl e
  930. | TType(t,_) -> TTypeDecl t
  931. | TAbstract(a,_) -> TAbstractDecl a
  932. | _ -> die "" __LOC__
  933. (*
  934. hxgen means if the type was generated by haxe. If a type was generated by haxe, it means
  935. it will contain special constructs for speedy reflection, for example
  936. @see SetHXGen module
  937. *)
  938. let rec is_hxgen md =
  939. match md with
  940. | TClassDecl cl -> Meta.has Meta.HxGen cl.cl_meta
  941. | TEnumDecl e -> Meta.has Meta.HxGen e.e_meta
  942. | TTypeDecl t -> Meta.has Meta.HxGen t.t_meta || ( match follow t.t_type with | TInst(cl,_) -> is_hxgen (TClassDecl cl) | TEnum(e,_) -> is_hxgen (TEnumDecl e) | _ -> false )
  943. | TAbstractDecl a -> Meta.has Meta.HxGen a.a_meta
  944. let is_hxgen_t t =
  945. match t with
  946. | TInst (cl, _) -> Meta.has Meta.HxGen cl.cl_meta
  947. | TEnum (e, _) -> Meta.has Meta.HxGen e.e_meta
  948. | TAbstract (a, _) -> Meta.has Meta.HxGen a.a_meta
  949. | TType (t, _) -> Meta.has Meta.HxGen t.t_meta
  950. | _ -> false
  951. let mt_to_t_dyn md =
  952. match md with
  953. | TClassDecl cl -> TInst(cl, List.map (fun _ -> t_dynamic) cl.cl_params)
  954. | TEnumDecl e -> TEnum(e, List.map (fun _ -> t_dynamic) e.e_params)
  955. | TAbstractDecl a -> TAbstract(a, List.map (fun _ -> t_dynamic) a.a_params)
  956. | TTypeDecl t -> TType(t, List.map (fun _ -> t_dynamic) t.t_params)
  957. (* replace open TMonos with TDynamic *)
  958. let rec replace_mono t =
  959. match t with
  960. | TMono t ->
  961. (match t.tm_type with
  962. | None -> Monomorph.bind t t_dynamic
  963. | Some _ -> ())
  964. | TEnum (_,p) | TInst (_,p) | TType (_,p) | TAbstract (_,p) ->
  965. List.iter replace_mono p
  966. | TFun (args,ret) ->
  967. List.iter (fun (_,_,t) -> replace_mono t) args;
  968. replace_mono ret
  969. | TAnon _
  970. | TDynamic _ -> ()
  971. | TLazy f ->
  972. replace_mono (lazy_type f)
  973. (* helper *)
  974. let mk_class_field ?(static = false) name t public pos kind params =
  975. let f = mk_field name ~public ~static t pos null_pos in
  976. f.cf_meta <- [ Meta.CompilerGenerated, [], null_pos ]; (* annotate that this class field was generated by the compiler *)
  977. f.cf_kind <- kind;
  978. f.cf_params <- params;
  979. f
  980. (* this helper just duplicates the type parameter class, which is assumed that cl is. *)
  981. (* This is so we can use class parameters on function parameters, without running the risk of name clash *)
  982. (* between both *)
  983. let map_param cl =
  984. let ret = mk_class cl.cl_module (fst cl.cl_path, snd cl.cl_path ^ "_c") cl.cl_pos null_pos in
  985. ret.cl_implements <- cl.cl_implements;
  986. ret.cl_kind <- cl.cl_kind;
  987. ret
  988. let get_cl_t t =
  989. match follow t with | TInst (cl,_) -> cl | _ -> die "" __LOC__
  990. let mk_class m path pos =
  991. let cl = Type.mk_class m path pos null_pos in
  992. cl.cl_meta <- [ Meta.CompilerGenerated, [], null_pos ];
  993. cl
  994. type tfield_access =
  995. | FClassField of tclass * tparams * tclass (* declared class *) * tclass_field * bool (* is static? *) * t (* the actual cf type, in relation to the class type params *) * t (* declared type *)
  996. | FEnumField of tenum * tenum_field * bool (* is parameterized enum ? *)
  997. | FAnonField of tclass_field
  998. | FDynamicField of t
  999. | FNotFound
  1000. let is_var f = match f.cf_kind with | Var _ -> true | _ -> false
  1001. let find_first_declared_field gen orig_cl ?get_vmtype ?exact_field field =
  1002. let get_vmtype = match get_vmtype with None -> (fun t -> t) | Some f -> f in
  1003. let chosen = ref None in
  1004. let is_overload = ref false in
  1005. let rec loop_cl depth c tl tlch =
  1006. (try
  1007. let ret = PMap.find field c.cl_fields in
  1008. if has_class_field_flag ret CfOverload then is_overload := true;
  1009. match !chosen, exact_field with
  1010. | Some(d,f,_,_,_), _ when depth <= d || (is_var ret && not (is_var f)) -> ()
  1011. | _, None ->
  1012. chosen := Some(depth,ret,c,tl,tlch)
  1013. | _, Some f2 ->
  1014. List.iter (fun f ->
  1015. let declared_t = apply_params c.cl_params tl f.cf_type in
  1016. if same_overload_args ~get_vmtype declared_t f2.cf_type f f2 then
  1017. chosen := Some(depth,f,c,tl,tlch)
  1018. ) (ret :: ret.cf_overloads)
  1019. with | Not_found -> ());
  1020. (match c.cl_super with
  1021. | Some (sup,stl) ->
  1022. let tl = List.map (apply_params c.cl_params tl) stl in
  1023. let stl = gen.greal_type_param (TClassDecl sup) stl in
  1024. let tlch = List.map (apply_params c.cl_params tlch) stl in
  1025. loop_cl (depth+1) sup tl tlch
  1026. | None -> ());
  1027. if (has_class_flag c CInterface) then
  1028. List.iter (fun (sup,stl) ->
  1029. let tl = List.map (apply_params c.cl_params tl) stl in
  1030. let stl = gen.greal_type_param (TClassDecl sup) stl in
  1031. let tlch = List.map (apply_params c.cl_params tlch) stl in
  1032. loop_cl (depth+1) sup tl tlch
  1033. ) c.cl_implements
  1034. in
  1035. loop_cl 0 orig_cl (extract_param_types orig_cl.cl_params) (extract_param_types orig_cl.cl_params);
  1036. match !chosen with
  1037. | None ->
  1038. None
  1039. | Some(_,f,c,tl,tlch) ->
  1040. if !is_overload && not (has_class_field_flag f CfOverload) then
  1041. add_class_field_flag f CfOverload;
  1042. let declared_t = apply_params c.cl_params tl f.cf_type in
  1043. let params_t = apply_params c.cl_params tlch f.cf_type in
  1044. let actual_t = match follow params_t with
  1045. | TFun(args,ret) -> TFun(List.map (fun (n,o,t) -> (n,o,gen.greal_type t)) args, gen.greal_type ret)
  1046. | _ -> gen.greal_type params_t in
  1047. Some(f,actual_t,declared_t,params_t,c,tl,tlch)
  1048. let rec field_access gen (t:t) (field:string) : (tfield_access) =
  1049. (*
  1050. t can be either an haxe-type as a real-type;
  1051. 'follow' should be applied here since we can generalize that a TType will be accessible as its
  1052. underlying type.
  1053. *)
  1054. (* let pointers to values be accessed as the underlying values *)
  1055. let t = match gen.greal_type t with
  1056. | TAbstract({ a_path = ["cs"],"Pointer" },[t]) ->
  1057. gen.greal_type t
  1058. | _ -> t
  1059. in
  1060. match follow t with
  1061. | TInst(cl, params) ->
  1062. let orig_cl = cl in
  1063. let orig_params = params in
  1064. let rec not_found cl params =
  1065. match cl.cl_dynamic with
  1066. | Some t ->
  1067. let t = apply_params cl.cl_params params t in
  1068. FDynamicField t
  1069. | None ->
  1070. match cl.cl_super with
  1071. | None -> FNotFound
  1072. | Some (super,p) -> not_found super p
  1073. in
  1074. let not_found () =
  1075. try
  1076. let cf = PMap.find field gen.gbase_class_fields in
  1077. FClassField (orig_cl, orig_params, gen.gclasses.cl_dyn, cf, false, cf.cf_type, cf.cf_type)
  1078. with
  1079. | Not_found -> not_found cl params
  1080. in
  1081. (* this is a hack for C#'s different generic types with same path *)
  1082. let hashtbl_field = (String.concat "" (List.map (fun _ -> "]") cl.cl_params)) ^ field in
  1083. let types = try
  1084. Hashtbl.find gen.greal_field_types (orig_cl.cl_path, hashtbl_field)
  1085. with | Not_found ->
  1086. let ret = find_first_declared_field gen cl field in
  1087. let ret = match ret with
  1088. | None -> None
  1089. | Some(cf,t,dt,_,cl,_,_) -> Some(cf,t,dt,cl)
  1090. in
  1091. if ret <> None then Hashtbl.add gen.greal_field_types (orig_cl.cl_path, hashtbl_field) ret;
  1092. ret
  1093. in
  1094. (match types with
  1095. | None -> not_found()
  1096. | Some (cf, actual_t, declared_t, declared_cl) ->
  1097. FClassField(orig_cl, orig_params, declared_cl, cf, false, actual_t, declared_t))
  1098. | TEnum (en,params) when Meta.has Meta.Class en.e_meta ->
  1099. (* A field access to an enum could mean accessing field of its generated class (e.g. `index` for switches).
  1100. Ideally, we should change all TEnum instances to relevant TInst instances so we never reach this case,
  1101. but for now, we're going to find the generated class and make a field access to it instead. *)
  1102. (try
  1103. let cl_enum = List.find (function TClassDecl cl when cl.cl_path = en.e_path && Meta.has Meta.Enum cl.cl_meta -> true | _ -> false) gen.gtypes_list in
  1104. let cl_enum = match cl_enum with TClassDecl cl -> TInst (cl,params) | _ -> die "" __LOC__ in
  1105. field_access gen cl_enum field
  1106. with Not_found ->
  1107. FNotFound)
  1108. | TAnon anon ->
  1109. (try match !(anon.a_status) with
  1110. | Statics cl ->
  1111. let cf = PMap.find field cl.cl_statics in
  1112. FClassField(cl, List.map (fun _ -> t_dynamic) cl.cl_params, cl, cf, true, cf.cf_type, cf.cf_type)
  1113. | EnumStatics e ->
  1114. let f = PMap.find field e.e_constrs in
  1115. let is_param = match follow f.ef_type with | TFun _ -> true | _ -> false in
  1116. FEnumField(e, f, is_param)
  1117. | _ when PMap.mem field gen.gbase_class_fields ->
  1118. let cf = PMap.find field gen.gbase_class_fields in
  1119. FClassField(gen.gclasses.cl_dyn, [t_dynamic], gen.gclasses.cl_dyn, cf, false, cf.cf_type, cf.cf_type)
  1120. | _ ->
  1121. FAnonField(PMap.find field anon.a_fields)
  1122. with | Not_found -> FNotFound)
  1123. | _ when PMap.mem field gen.gbase_class_fields ->
  1124. let cf = PMap.find field gen.gbase_class_fields in
  1125. FClassField(gen.gclasses.cl_dyn, [t_dynamic], gen.gclasses.cl_dyn, cf, false, cf.cf_type, cf.cf_type)
  1126. | TDynamic t -> FDynamicField (match t with None -> t_dynamic | Some t -> t)
  1127. | TMono _ -> FDynamicField t_dynamic
  1128. | _ -> FNotFound
  1129. let field_access_esp gen t field = match field with
  1130. | FStatic(cl,cf) | FInstance(cl,_,cf) when has_class_field_flag cf CfExtern ->
  1131. let static = match field with
  1132. | FStatic _ -> true
  1133. | _ -> false
  1134. in
  1135. let p = match follow (run_follow gen t) with
  1136. | TInst(_,p) -> p
  1137. | _ -> extract_param_types cl.cl_params
  1138. in
  1139. FClassField(cl,p,cl,cf,static,cf.cf_type,cf.cf_type)
  1140. | _ -> field_access gen t (field_name field)
  1141. let mk_field_access gen expr field pos =
  1142. match field_access gen expr.etype field with
  1143. | FClassField(c,p,dc,cf,false,at,_) ->
  1144. { eexpr = TField(expr, FInstance(dc,p,cf)); etype = apply_params c.cl_params p at; epos = pos }
  1145. | FClassField(c,p,dc,cf,true,at,_) ->
  1146. { eexpr = TField(expr, FStatic(dc,cf)); etype = at; epos = pos }
  1147. | FAnonField cf ->
  1148. { eexpr = TField(expr, FAnon cf); etype = cf.cf_type; epos = pos }
  1149. | FDynamicField t ->
  1150. { eexpr = TField(expr, FDynamic field); etype = t; epos = pos }
  1151. | FNotFound ->
  1152. { eexpr = TField(expr, FDynamic field); etype = t_dynamic; epos = pos }
  1153. | FEnumField _ -> die "" __LOC__
  1154. (* ******************************************* *)
  1155. (* Module dependency resolution *)
  1156. (* ******************************************* *)
  1157. type t_dependency =
  1158. | DAfter of float
  1159. | DBefore of float
  1160. exception ImpossibleDependency of string
  1161. let max_dep = 10000.0
  1162. let min_dep = - (10000.0)
  1163. let solve_deps name (deps:t_dependency list) =
  1164. let vmin = min_dep -. 1.0 in
  1165. let vmax = max_dep +. 1.0 in
  1166. let rec loop dep vmin vmax =
  1167. match dep with
  1168. | [] ->
  1169. (if vmin >= vmax then raise (ImpossibleDependency name));
  1170. (vmin +. vmax) /. 2.0
  1171. | head :: tail ->
  1172. match head with
  1173. | DBefore f ->
  1174. loop tail (max vmin f) vmax
  1175. | DAfter f ->
  1176. loop tail vmin (min vmax f)
  1177. in
  1178. loop deps vmin vmax
  1179. (* type resolution *)
  1180. exception TypeNotFound of path
  1181. let get_type gen path =
  1182. try Hashtbl.find gen.gtypes path with | Not_found -> raise (TypeNotFound path)
  1183. let fun_args l =
  1184. List.map (fun (v,s) -> (v.v_name, (s <> None), v.v_type)) l