common.ml 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. (*
  2. The Haxe Compiler
  3. Copyright (C) 2005-2016 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. open Ast
  17. open Type
  18. type package_rule =
  19. | Forbidden
  20. | Directory of string
  21. | Remap of string
  22. type pos = Ast.pos
  23. type basic_types = {
  24. mutable tvoid : t;
  25. mutable tint : t;
  26. mutable tfloat : t;
  27. mutable tbool : t;
  28. mutable tnull : t -> t;
  29. mutable tstring : t;
  30. mutable tarray : t -> t;
  31. }
  32. type stats = {
  33. s_files_parsed : int ref;
  34. s_classes_built : int ref;
  35. s_methods_typed : int ref;
  36. s_macros_called : int ref;
  37. }
  38. type platform =
  39. | Cross
  40. | Js
  41. | Neko
  42. | Flash
  43. | Php
  44. | Cpp
  45. | Cs
  46. | Java
  47. | Python
  48. (**
  49. The capture policy tells which handling we make of captured locals
  50. (the locals which are referenced in local functions)
  51. See details/implementation in Codegen.captured_vars
  52. *)
  53. type capture_policy =
  54. (** do nothing, let the platform handle it *)
  55. | CPNone
  56. (** wrap all captured variables into a single-element array to allow modifications *)
  57. | CPWrapRef
  58. (** similar to wrap ref, but will only apply to the locals that are declared in loops *)
  59. | CPLoopVars
  60. type platform_config = {
  61. (** has a static type system, with not-nullable basic types (Int/Float/Bool) *)
  62. pf_static : bool;
  63. (** has access to the "sys" package *)
  64. pf_sys : bool;
  65. (** local variables are block-scoped *)
  66. pf_locals_scope : bool;
  67. (** captured local variables are scoped *)
  68. pf_captured_scope : bool;
  69. (** generated locals must be absolutely unique wrt the current function *)
  70. pf_unique_locals : bool;
  71. (** captured variables handling (see before) *)
  72. pf_capture_policy : capture_policy;
  73. (** when calling a method with optional args, do we replace the missing args with "null" constants *)
  74. pf_pad_nulls : bool;
  75. (** add a final return to methods not having one already - prevent some compiler warnings *)
  76. pf_add_final_return : bool;
  77. (** does the platform natively support overloaded functions *)
  78. pf_overload : bool;
  79. (** does the platform generator handle pattern matching *)
  80. pf_pattern_matching : bool;
  81. (** can the platform use default values for non-nullable arguments *)
  82. pf_can_skip_non_nullable_argument : bool;
  83. (** type paths that are reserved on the platform *)
  84. pf_reserved_type_paths : path list;
  85. }
  86. type display_mode =
  87. | DMNone
  88. | DMDefault
  89. | DMUsage
  90. | DMPosition
  91. | DMToplevel
  92. | DMResolve of string
  93. | DMType
  94. type context = {
  95. (* config *)
  96. version : int;
  97. args : string list;
  98. mutable sys_args : string list;
  99. mutable display : display_mode;
  100. mutable debug : bool;
  101. mutable verbose : bool;
  102. mutable foptimize : bool;
  103. mutable platform : platform;
  104. mutable config : platform_config;
  105. mutable std_path : string list;
  106. mutable class_path : string list;
  107. mutable main_class : Type.path option;
  108. mutable defines : (string,string) PMap.t;
  109. mutable package_rules : (string,package_rule) PMap.t;
  110. mutable error : string -> pos -> unit;
  111. mutable warning : string -> pos -> unit;
  112. mutable load_extern_type : (path -> pos -> (string * Ast.package) option) list; (* allow finding types which are not in sources *)
  113. mutable filters : (unit -> unit) list;
  114. mutable final_filters : (unit -> unit) list;
  115. mutable defines_signature : string option;
  116. mutable print : string -> unit;
  117. mutable get_macros : unit -> context option;
  118. mutable run_command : string -> int;
  119. file_lookup_cache : (string,string option) Hashtbl.t;
  120. parser_cache : (string,string list * (type_def * pos) list) Hashtbl.t;
  121. mutable stored_typed_exprs : (int, texpr) PMap.t;
  122. (* output *)
  123. mutable file : string;
  124. mutable flash_version : float;
  125. mutable features : (string,bool) Hashtbl.t;
  126. mutable modules : Type.module_def list;
  127. mutable main : Type.texpr option;
  128. mutable types : Type.module_type list;
  129. mutable resources : (string,string) Hashtbl.t;
  130. mutable neko_libs : string list;
  131. mutable include_files : (string * string) list;
  132. mutable php_front : string option;
  133. mutable php_lib : string option;
  134. mutable php_prefix : string option;
  135. mutable swf_libs : (string * (unit -> Swf.swf) * (unit -> ((string list * string),As3hl.hl_class) Hashtbl.t)) list;
  136. mutable java_libs : (string * bool * (unit -> unit) * (unit -> (path list)) * (path -> ((JData.jclass * string * string) option))) list; (* (path,std,close,all_files,lookup) *)
  137. mutable net_libs : (string * bool * (unit -> path list) * (path -> IlData.ilclass option)) list; (* (path,std,all_files,lookup) *)
  138. mutable net_std : string list;
  139. net_path_map : (path,string list * string list * string) Hashtbl.t;
  140. mutable c_args : string list;
  141. mutable js_gen : (unit -> unit) option;
  142. (* typing *)
  143. mutable basic : basic_types;
  144. memory_marker : float array;
  145. }
  146. exception Abort of string * Ast.pos
  147. let display_default = ref DMNone
  148. module Define = struct
  149. type strict_defined =
  150. | AbsolutePath
  151. | AdvancedTelemetry
  152. | Analyzer
  153. | As3
  154. | CheckXmlProxy
  155. | CoreApi
  156. | CoreApiSerialize
  157. | Cppia
  158. | Dce
  159. | DceDebug
  160. | Debug
  161. | Display
  162. | DllExport
  163. | DllImport
  164. | DocGen
  165. | Dump
  166. | DumpDependencies
  167. | DumpIgnoreVarIds
  168. | DynamicInterfaceClosures
  169. | EraseGenerics
  170. | Fdb
  171. | FileExtension
  172. | FlashStrict
  173. | FlashUseStage
  174. | ForceLibCheck
  175. | ForceNativeProperty
  176. | FormatWarning
  177. | GencommonDebug
  178. | HaxeBoot
  179. | HaxeVer
  180. | HxcppApiLevel
  181. | IncludePrefix
  182. | Interp
  183. | JavaVer
  184. | JqueryVer
  185. | JsClassic
  186. | JsEs5
  187. | JsUnflatten
  188. | KeepOldOutput
  189. | LoopUnrollMaxCost
  190. | Macro
  191. | MacroTimes
  192. | NekoSource
  193. | NekoV1
  194. | NetworkSandbox
  195. | NetVer
  196. | NetTarget
  197. | NoCompilation
  198. | NoCOpt
  199. | NoDeprecationWarnings
  200. | NoFlashOverride
  201. | NoDebug
  202. | NoInline
  203. | NoOpt
  204. | NoPatternMatching
  205. | NoRoot
  206. | NoSwfCompress
  207. | NoTraces
  208. | Objc
  209. | PhpPrefix
  210. | RealPosition
  211. | ReplaceFiles
  212. | Scriptable
  213. | ShallowExpose
  214. | SourceHeader
  215. | SourceMapContent
  216. | Swc
  217. | SwfCompressLevel
  218. | SwfDebugPassword
  219. | SwfDirectBlit
  220. | SwfGpu
  221. | SwfMetadata
  222. | SwfPreloaderFrame
  223. | SwfProtected
  224. | SwfScriptTimeout
  225. | SwfUseDoAbc
  226. | Sys
  227. | Unsafe
  228. | UseNekoc
  229. | UseRttiDoc
  230. | Vcproj
  231. | NoMacroCache
  232. | Last (* must be last *)
  233. let infos = function
  234. | AbsolutePath -> ("absolute_path","Print absolute file path in trace output")
  235. | AdvancedTelemetry -> ("advanced-telemetry","Allow the SWF to be measured with Monocle tool")
  236. | Analyzer -> ("analyzer","Use static analyzer for optimization (experimental)")
  237. | As3 -> ("as3","Defined when outputing flash9 as3 source code")
  238. | CheckXmlProxy -> ("check_xml_proxy","Check the used fields of the xml proxy")
  239. | CoreApi -> ("core_api","Defined in the core api context")
  240. | CoreApiSerialize -> ("core_api_serialize","Mark some generated core api classes with the Serializable attribute on C#")
  241. | Cppia -> ("cppia", "Generate experimental cpp instruction assembly")
  242. | Dce -> ("dce","<mode:std|full||no> Set the dead code elimination mode (default std)")
  243. | DceDebug -> ("dce_debug","Show DCE log")
  244. | Debug -> ("debug","Activated when compiling with -debug")
  245. | Display -> ("display","Activated during completion")
  246. | DllExport -> ("dll_export", "GenCPP experimental linking")
  247. | DllImport -> ("dll_import", "GenCPP experimental linking")
  248. | DocGen -> ("doc_gen","Do not perform any removal/change in order to correctly generate documentation")
  249. | Dump -> ("dump","Dump the complete typed AST for internal debugging in a dump subdirectory - use dump=pretty for Haxe-like formatting")
  250. | DumpDependencies -> ("dump_dependencies","Dump the classes dependencies in a dump subdirectory")
  251. | DumpIgnoreVarIds -> ("dump_ignore_var_ids","Remove variable IDs from non-pretty dumps (helps with diff)")
  252. | DynamicInterfaceClosures -> ("dynamic_interface_closures","Use slow path for interface closures to save space")
  253. | EraseGenerics -> ("erase_generics","Erase generic classes on C#")
  254. | Fdb -> ("fdb","Enable full flash debug infos for FDB interactive debugging")
  255. | FileExtension -> ("file_extension","Output filename extension for cpp source code")
  256. | FlashStrict -> ("flash_strict","More strict typing for flash target")
  257. | FlashUseStage -> ("flash_use_stage","Keep the SWF library initial stage")
  258. (* force_lib_check is only here as a debug facility - compiler checking allows errors to be found more easily *)
  259. | ForceLibCheck -> ("force_lib_check","Force the compiler to check -net-lib and -java-lib added classes (internal)")
  260. | ForceNativeProperty -> ("force_native_property","Tag all properties with :nativeProperty metadata for 3.1 compatibility")
  261. | FormatWarning -> ("format_warning","Print a warning for each formated string, for 2.x compatibility")
  262. | GencommonDebug -> ("gencommon_debug","GenCommon internal")
  263. | HaxeBoot -> ("haxe_boot","Given the name 'haxe' to the flash boot class instead of a generated name")
  264. | HaxeVer -> ("haxe_ver","The current Haxe version value")
  265. | HxcppApiLevel -> ("hxcpp_api_level","Provided to allow compatibility between hxcpp versions")
  266. | IncludePrefix -> ("include_prefix","prepend path to generated include files")
  267. | Interp -> ("interp","The code is compiled to be run with --interp")
  268. | JavaVer -> ("java_ver", "<version:5-7> Sets the Java version to be targeted")
  269. | JqueryVer -> ("jquery_ver", "The jQuery version supported by js.jquery.*. The version is encoded as an interger. e.g. 1.11.3 is encoded as 11103")
  270. | JsClassic -> ("js_classic","Don't use a function wrapper and strict mode in JS output")
  271. | JsEs5 -> ("js_es5","Generate JS for ES5-compliant runtimes")
  272. | JsUnflatten -> ("js_unflatten","Generate nested objects for packages and types")
  273. | KeepOldOutput -> ("keep_old_output","Keep old source files in the output directory (for C#/Java)")
  274. | LoopUnrollMaxCost -> ("loop_unroll_max_cost","Maximum cost (number of expressions * iterations) before loop unrolling is canceled (default 250)")
  275. | Macro -> ("macro","Defined when code is compiled in the macro context")
  276. | MacroTimes -> ("macro_times","Display per-macro timing when used with --times")
  277. | NetVer -> ("net_ver", "<version:20-45> Sets the .NET version to be targeted")
  278. | NetTarget -> ("net_target", "<name> Sets the .NET target. Defaults to \"net\". xbox, micro (Micro Framework), compact (Compact Framework) are some valid values")
  279. | NekoSource -> ("neko_source","Output neko source instead of bytecode")
  280. | NekoV1 -> ("neko_v1","Keep Neko 1.x compatibility")
  281. | NetworkSandbox -> ("network-sandbox","Use local network sandbox instead of local file access one")
  282. | NoCompilation -> ("no-compilation","Disable final compilation for Cs, Cpp and Java")
  283. | NoCOpt -> ("no_copt","Disable completion optimization (for debug purposes)")
  284. | NoDebug -> ("no_debug","Remove all debug macros from cpp output")
  285. | NoDeprecationWarnings -> ("no-deprecation-warnings","Do not warn if fields annotated with @:deprecated are used")
  286. | NoFlashOverride -> ("no-flash-override", "Change overrides on some basic classes into HX suffixed methods, flash only")
  287. | NoOpt -> ("no_opt","Disable optimizations")
  288. | NoPatternMatching -> ("no_pattern_matching","Disable pattern matching")
  289. | NoInline -> ("no_inline","Disable inlining")
  290. | NoRoot -> ("no_root","Generate top-level types into haxe.root namespace")
  291. | NoMacroCache -> ("no_macro_cache","Disable macro context caching")
  292. | NoSwfCompress -> ("no_swf_compress","Disable SWF output compression")
  293. | NoTraces -> ("no_traces","Disable all trace calls")
  294. | Objc -> ("objc","Sets the hxcpp output to objective-c++ classes. Must be defined for interop")
  295. | PhpPrefix -> ("php_prefix","Compiled with --php-prefix")
  296. | RealPosition -> ("real_position","Disables Haxe source mapping when targetting C#, removes position comments in Java output")
  297. | ReplaceFiles -> ("replace_files","GenCommon internal")
  298. | Scriptable -> ("scriptable","GenCPP internal")
  299. | ShallowExpose -> ("shallow-expose","Expose types to surrounding scope of Haxe generated closure without writing to window object")
  300. | SourceHeader -> ("source-header","Print value as comment on top of generated files, use '' value to disable")
  301. | SourceMapContent -> ("source-map-content","Include the hx sources as part of the JS source map")
  302. | Swc -> ("swc","Output a SWC instead of a SWF")
  303. | SwfCompressLevel -> ("swf_compress_level","<level:1-9> Set the amount of compression for the SWF output")
  304. | SwfDebugPassword -> ("swf_debug_password", "Set a password for debugging")
  305. | SwfDirectBlit -> ("swf_direct_blit", "Use hardware acceleration to blit graphics")
  306. | SwfGpu -> ("swf_gpu", "Use GPU compositing features when drawing graphics")
  307. | SwfMetadata -> ("swf_metadata", "<file> Include contents of <file> as metadata in the swf")
  308. | SwfPreloaderFrame -> ("swf_preloader_frame", "Insert empty first frame in swf")
  309. | SwfProtected -> ("swf_protected","Compile Haxe private as protected in the SWF instead of public")
  310. | SwfScriptTimeout -> ("swf_script_timeout", "Maximum ActionScript processing time before script stuck dialog box displays (in seconds)")
  311. | SwfUseDoAbc -> ("swf_use_doabc", "Use DoAbc swf-tag instead of DoAbcDefine")
  312. | Sys -> ("sys","Defined for all system platforms")
  313. | Unsafe -> ("unsafe","Allow unsafe code when targeting C#")
  314. | UseNekoc -> ("use_nekoc","Use nekoc compiler instead of internal one")
  315. | UseRttiDoc -> ("use_rtti_doc","Allows access to documentation during compilation")
  316. | Vcproj -> ("vcproj","GenCPP internal")
  317. | Last -> assert false
  318. end
  319. module MetaInfo = struct
  320. open Meta
  321. type meta_usage =
  322. | TClass
  323. | TClassField
  324. | TAbstract
  325. | TAbstractField
  326. | TEnum
  327. | TTypedef
  328. | TAnyField
  329. | TExpr
  330. | TTypeParameter
  331. type meta_parameter =
  332. | HasParam of string
  333. | Platform of platform
  334. | Platforms of platform list
  335. | UsedOn of meta_usage
  336. | UsedOnEither of meta_usage list
  337. | Internal
  338. let to_string = function
  339. | Abi -> ":abi",("Function ABI/calling convention",[Platforms [Cpp]])
  340. | Abstract -> ":abstract",("Sets the underlying class implementation as 'abstract'",[Platforms [Java;Cs]])
  341. | Access -> ":access",("Forces private access to package, type or field",[HasParam "Target path";UsedOnEither [TClass;TClassField]])
  342. | Accessor -> ":accessor",("Used internally by DCE to mark property accessors",[UsedOn TClassField;Internal])
  343. | Allow -> ":allow",("Allows private access from package, type or field",[HasParam "Target path";UsedOnEither [TClass;TClassField]])
  344. | Analyzer -> ":analyzer",("Used to configure the static analyzer",[])
  345. | Annotation -> ":annotation",("Annotation (@interface) definitions on -java-lib imports will be annotated with this metadata. Has no effect on types compiled by Haxe",[Platform Java; UsedOn TClass])
  346. | ArrayAccess -> ":arrayAccess",("Allows [] access on an abstract",[UsedOnEither [TAbstract;TAbstractField]])
  347. | Ast -> ":ast",("Internally used to pass the AST source into the typed AST",[Internal])
  348. | AstSource -> ":astSource",("Filled by the compiler with the parsed expression of the field",[UsedOn TClassField])
  349. | AutoBuild -> ":autoBuild",("Extends @:build metadata to all extending and implementing classes",[HasParam "Build macro call";UsedOn TClass])
  350. | Bind -> ":bind",("Override Swf class declaration",[Platform Flash;UsedOn TClass])
  351. | Bitmap -> ":bitmap",("Embeds given bitmap data into the class (must extend flash.display.BitmapData)",[HasParam "Bitmap file path";UsedOn TClass;Platform Flash])
  352. | BridgeProperties -> ":bridgeProperties",("Creates native property bridges for all Haxe properties in this class",[UsedOn TClass;Platform Cs])
  353. | Build -> ":build",("Builds a class or enum from a macro",[HasParam "Build macro call";UsedOnEither [TClass;TEnum]])
  354. | BuildXml -> ":buildXml",("Specify xml data to be injected into Build.xml",[Platform Cpp])
  355. | Callable -> ":callable",("Abstract forwards call to its underlying type",[UsedOn TAbstract])
  356. | Class -> ":class",("Used internally to annotate an enum that will be generated as a class",[Platforms [Java;Cs]; UsedOn TEnum; Internal])
  357. | ClassCode -> ":classCode",("Used to inject platform-native code into a class",[Platforms [Java;Cs]; UsedOn TClass])
  358. | Commutative -> ":commutative",("Declares an abstract operator as commutative",[UsedOn TAbstractField])
  359. | CompilerGenerated -> ":compilerGenerated",("Marks a field as generated by the compiler. Shouldn't be used by the end user",[Platforms [Java;Cs]])
  360. | Const -> ":const",("Allows a type parameter to accept expression values",[UsedOn TTypeParameter])
  361. | CoreApi -> ":coreApi",("Identifies this class as a core api class (forces Api check)",[UsedOnEither [TClass;TEnum;TTypedef;TAbstract]])
  362. | CoreType -> ":coreType",("Identifies an abstract as core type so that it requires no implementation",[UsedOn TAbstract])
  363. | CppFileCode -> ":cppFileCode",("Code to be injected into generated cpp file",[Platform Cpp])
  364. | CppInclude -> ":cppInclude",("File to be included in generated cpp file",[Platform Cpp])
  365. | CppNamespaceCode -> ":cppNamespaceCode",("",[Platform Cpp])
  366. | CsNative -> ":csNative",("Automatically added by -net-lib on classes generated from .NET DLL files",[Platform Cs; UsedOnEither[TClass;TEnum]; Internal])
  367. | Dce -> ":dce",("Forces dead code elimination even when -dce full is not specified",[UsedOnEither [TClass;TEnum]])
  368. | Debug -> ":debug",("Forces debug information to be generated into the Swf even without -debug",[UsedOnEither [TClass;TClassField]; Platform Flash])
  369. | Decl -> ":decl",("",[Platform Cpp])
  370. | DefParam -> ":defParam",("?",[])
  371. | Delegate -> ":delegate",("Automatically added by -net-lib on delegates",[Platform Cs; UsedOn TAbstract])
  372. | Depend -> ":depend",("",[Platform Cpp])
  373. | Deprecated -> ":deprecated",("Mark a type or field as deprecated",[])
  374. | DirectlyUsed -> ":directlyUsed",("Marks types that are directly referenced by non-extern code",[Internal])
  375. | DynamicObject -> ":dynamicObject",("Used internally to identify the Dynamic Object implementation",[Platforms [Java;Cs]; UsedOn TClass; Internal])
  376. | Enum -> ":enum",("Defines finite value sets to abstract definitions",[UsedOn TAbstract])
  377. | EnumConstructorParam -> ":enumConstructorParam",("Used internally to annotate GADT type parameters",[UsedOn TClass; Internal])
  378. | Event -> ":event",("Automatically added by -net-lib on events. Has no effect on types compiled by Haxe",[Platform Cs; UsedOn TClassField])
  379. | Exhaustive -> ":exhaustive",("",[Internal])
  380. | Expose -> ":expose",("Makes the class available on the window object",[HasParam "?Name=Class path";UsedOn TClass;Platform Js])
  381. | Extern -> ":extern",("Marks the field as extern so it is not generated",[UsedOn TClassField])
  382. | FakeEnum -> ":fakeEnum",("Treat enum as collection of values of the specified type",[HasParam "Type name";UsedOn TEnum])
  383. | File -> ":file",("Includes a given binary file into the target Swf and associates it with the class (must extend flash.utils.ByteArray)",[HasParam "File path";UsedOn TClass;Platform Flash])
  384. | Final -> ":final",("Prevents a class from being extended",[UsedOn TClass])
  385. | FlatEnum -> ":flatEnum",("Internally used to mark an enum as being flat, i.e. having no function constructors",[UsedOn TEnum; Internal])
  386. | Font -> ":font",("Embeds the given TrueType font into the class (must extend flash.text.Font)",[HasParam "TTF path";HasParam "Range String";UsedOn TClass])
  387. | Forward -> ":forward",("Forwards field access to underlying type",[HasParam "List of field names";UsedOn TAbstract])
  388. | ForwardStatics -> ":forwardStatics",("Forwards static field access to underlying type",[HasParam "List of field names";UsedOn TAbstract])
  389. | From -> ":from",("Specifies that the field of the abstract is a cast operation from the type identified in the function",[UsedOn TAbstractField])
  390. | FunctionCode -> ":functionCode",("Used to inject platform-native code into a function",[Platforms [Cpp;Java;Cs]])
  391. | FunctionTailCode -> ":functionTailCode",("",[Platform Cpp])
  392. | Generic -> ":generic",("Marks a class or class field as generic so each type parameter combination generates its own type/field",[UsedOnEither [TClass;TClassField]])
  393. | GenericBuild -> ":genericBuild",("Builds instances of a type using the specified macro",[UsedOn TClass])
  394. | GenericInstance -> ":genericInstance",("Internally used to mark instances of @:generic methods",[UsedOn TClassField;Internal])
  395. | Getter -> ":getter",("Generates a native getter function on the given field",[HasParam "Class field name";UsedOn TClassField;Platform Flash])
  396. | Hack -> ":hack",("Allows extending classes marked as @:final",[UsedOn TClass])
  397. | HasUntyped -> (":has_untyped",("Used by the typer to mark fields that have untyped expressions",[Internal]))
  398. | HaxeGeneric -> ":haxeGeneric",("Used internally to annotate non-native generic classes",[Platform Cs; UsedOnEither[TClass;TEnum]; Internal])
  399. | HeaderClassCode -> ":headerClassCode",("Code to be injected into the generated class, in the header",[Platform Cpp])
  400. | HeaderCode -> ":headerCode",("Code to be injected into the generated header file",[Platform Cpp])
  401. | HeaderInclude -> ":headerInclude",("File to be included in generated header file",[Platform Cpp])
  402. | HeaderNamespaceCode -> ":headerNamespaceCode",("",[Platform Cpp])
  403. | HxGen -> ":hxGen",("Annotates that an extern class was generated by Haxe",[Platforms [Java;Cs]; UsedOnEither [TClass;TEnum]])
  404. | IfFeature -> ":ifFeature",("Causes a field to be kept by DCE if the given feature is part of the compilation",[HasParam "Feature name";UsedOn TClassField])
  405. | Impl -> ":impl",("Used internally to mark abstract implementation fields",[UsedOn TAbstractField; Internal])
  406. | PythonImport -> ":pythonImport",("Generates python import statement for extern classes",[Platforms [Python]; UsedOn TClass])
  407. | ImplicitCast -> ":implicitCast",("Generated automatically on the AST when an implicit abstract cast happens",[Internal; UsedOn TExpr])
  408. | Include -> ":include",("",[Platform Cpp])
  409. | InitPackage -> ":initPackage",("?",[])
  410. | Meta.Internal -> ":internal",("Generates the annotated field/class with 'internal' access",[Platforms [Java;Cs]; UsedOnEither[TClass;TEnum;TClassField]])
  411. | IsVar -> ":isVar",("Forces a physical field to be generated for properties that otherwise would not require one",[UsedOn TClassField])
  412. | JavaCanonical -> ":javaCanonical",("Used by the Java target to annotate the canonical path of the type",[HasParam "Output type package";HasParam "Output type name";UsedOnEither [TClass;TEnum]; Platform Java])
  413. | JavaNative -> ":javaNative",("Automatically added by -java-lib on classes generated from JAR/class files",[Platform Java; UsedOnEither[TClass;TEnum]; Internal])
  414. | JsRequire -> ":jsRequire",("Generate javascript module require expression for given extern",[Platform Js; UsedOn TClass])
  415. | Keep -> ":keep",("Causes a field or type to be kept by DCE",[])
  416. | KeepInit -> ":keepInit",("Causes a class to be kept by DCE even if all its field are removed",[UsedOn TClass])
  417. | KeepSub -> ":keepSub",("Extends @:keep metadata to all implementing and extending classes",[UsedOn TClass])
  418. | LibType -> ":libType",("Used by -net-lib and -java-lib to mark a class that shouldn't be checked (overrides, interfaces, etc) by the type loader",[Internal; UsedOn TClass; Platforms [Java;Cs]])
  419. | Meta -> ":meta",("Internally used to mark a class field as being the metadata field",[])
  420. | Macro -> ":macro",("(deprecated)",[])
  421. | MaybeUsed -> ":maybeUsed",("Internally used by DCE to mark fields that might be kept",[Internal])
  422. | MergeBlock -> ":mergeBlock",("Merge the annotated block into the current scope",[UsedOn TExpr])
  423. | MultiType -> ":multiType",("Specifies that an abstract chooses its this-type from its @:to functions",[UsedOn TAbstract; HasParam "Relevant type parameters"])
  424. | Native -> ":native",("Rewrites the path of a class or enum during generation",[HasParam "Output type path";UsedOnEither [TClass;TEnum]])
  425. | NativeChildren -> ":nativeChildren",("Annotates that all children from a type should be treated as if it were an extern definition - platform native",[Platforms [Java;Cs]; UsedOn TClass])
  426. | NativeGen -> ":nativeGen",("Annotates that a type should be treated as if it were an extern definition - platform native",[Platforms [Java;Cs;Python]; UsedOnEither[TClass;TEnum]])
  427. | NativeGeneric -> ":nativeGeneric",("Used internally to annotate native generic classes",[Platform Cs; UsedOnEither[TClass;TEnum]; Internal])
  428. | NativeProperty -> ":nativeProperty",("Use native properties which will execute even with dynamic usage",[Platform Cpp])
  429. | NoCompletion -> ":noCompletion",("Prevents the compiler from suggesting completion on this field",[UsedOn TClassField])
  430. | NoDebug -> ":noDebug",("Does not generate debug information into the Swf even if -debug is set",[UsedOnEither [TClass;TClassField];Platform Flash])
  431. | NoDoc -> ":noDoc",("Prevents a type from being included in documentation generation",[])
  432. | NoExpr -> ":noExpr",("Internally used to mark abstract fields which have no expression by design",[Internal])
  433. | NoImportGlobal -> ":noImportGlobal",("Prevents a static field from being imported with import Class.*",[UsedOn TAnyField])
  434. | NonVirtual -> ":nonVirtual",("Declares function to be non-virtual in cpp",[Platform Cpp])
  435. | NoPackageRestrict -> ":noPackageRestrict",("Allows a module to be accessed across all targets if found on its first type",[Internal])
  436. | NoPrivateAccess -> ":noPrivateAccess",("Disallow private access to anything for the annotated expression",[UsedOn TExpr])
  437. | NoStack -> ":noStack",("",[Platform Cpp])
  438. | NotNull -> ":notNull",("Declares an abstract type as not accepting null values",[UsedOn TAbstract])
  439. | NoUsing -> ":noUsing",("Prevents a field from being used with 'using'",[UsedOn TClassField])
  440. | Ns -> ":ns",("Internally used by the Swf generator to handle namespaces",[Platform Flash])
  441. | Objc -> ":objc",("Declares a class or interface that is used to interoperate with Objective-C code",[Platform Cpp;UsedOn TClass])
  442. | Op -> ":op",("Declares an abstract field as being an operator overload",[HasParam "The operation";UsedOn TAbstractField])
  443. | Optional -> ":optional",("Marks the field of a structure as optional",[UsedOn TClassField])
  444. | Overload -> ":overload",("Allows the field to be called with different argument types",[HasParam "Function specification (no expression)";UsedOn TClassField])
  445. | Public -> ":public",("Marks a class field as being public",[UsedOn TClassField])
  446. | PublicFields -> ":publicFields",("Forces all class fields of inheriting classes to be public",[UsedOn TClass])
  447. | QuotedField -> ":quotedField",("Used internally to mark structure fields which are quoted in syntax",[Internal])
  448. | PrivateAccess -> ":privateAccess",("Allow private access to anything for the annotated expression",[UsedOn TExpr])
  449. | Protected -> ":protected",("Marks a class field as being protected",[UsedOn TClassField])
  450. | Property -> ":property",("Marks a property field to be compiled as a native C# property",[UsedOn TClassField;Platform Cs])
  451. | ReadOnly -> ":readOnly",("Generates a field with the 'readonly' native keyword",[Platform Cs; UsedOn TClassField])
  452. | RealPath -> ":realPath",("Internally used on @:native types to retain original path information",[Internal])
  453. | Remove -> ":remove",("Causes an interface to be removed from all implementing classes before generation",[UsedOn TClass])
  454. | Require -> ":require",("Allows access to a field only if the specified compiler flag is set",[HasParam "Compiler flag to check";UsedOn TClassField])
  455. | RequiresAssign -> ":requiresAssign",("Used internally to mark certain abstract operator overloads",[Internal])
  456. | Resolve -> ":resolve",("Abstract fields marked with this metadata can be used to resolve unknown fields",[UsedOn TClassField])
  457. | ReplaceReflection -> ":replaceReflection",("Used internally to specify a function that should replace its internal __hx_functionName counterpart",[Platforms [Java;Cs]; UsedOnEither[TClass;TEnum]; Internal])
  458. | Rtti -> ":rtti",("Adds runtime type informations",[UsedOn TClass])
  459. | Runtime -> ":runtime",("?",[])
  460. | RuntimeValue -> ":runtimeValue",("Marks an abstract as being a runtime value",[UsedOn TAbstract])
  461. | SelfCall -> ":selfCall",("Translates method calls into calling object directly",[UsedOn TClassField; Platform Js])
  462. | Setter -> ":setter",("Generates a native setter function on the given field",[HasParam "Class field name";UsedOn TClassField;Platform Flash])
  463. | StoredTypedExpr -> ":storedTypedExpr",("Used internally to reference a typed expression returned from a macro",[Internal])
  464. | SkipCtor -> ":skipCtor",("Used internally to generate a constructor as if it were a native type (no __hx_ctor)",[Platforms [Java;Cs]; Internal])
  465. | SkipReflection -> ":skipReflection",("Used internally to annotate a field that shouldn't have its reflection data generated",[Platforms [Java;Cs]; UsedOn TClassField; Internal])
  466. | Sound -> ":sound",( "Includes a given .wav or .mp3 file into the target Swf and associates it with the class (must extend flash.media.Sound)",[HasParam "File path";UsedOn TClass;Platform Flash])
  467. | SourceFile -> ":sourceFile",("Source code filename for external class",[Platform Cpp])
  468. | Strict -> ":strict",("Used to declare a native C# attribute or a native Java metadata. Is type checked",[Platforms [Java;Cs]])
  469. | Struct -> ":struct",("Marks a class definition as a struct",[Platform Cs; UsedOn TClass])
  470. | StructAccess -> ":structAccess",("Marks an extern class as using struct access('.') not pointer('->')",[Platform Cpp; UsedOn TClass])
  471. | SuppressWarnings -> ":suppressWarnings",("Adds a SuppressWarnings annotation for the generated Java class",[Platform Java; UsedOn TClass])
  472. | Throws -> ":throws",("Adds a 'throws' declaration to the generated function",[HasParam "Type as String"; Platform Java; UsedOn TClassField])
  473. | This -> ":this",("Internally used to pass a 'this' expression to macros",[Internal; UsedOn TExpr])
  474. | To -> ":to",("Specifies that the field of the abstract is a cast operation to the type identified in the function",[UsedOn TAbstractField])
  475. | ToString -> ":toString",("Internally used",[Internal])
  476. | Transient -> ":transient",("Adds the 'transient' flag to the class field",[Platform Java; UsedOn TClassField])
  477. | ValueUsed -> ":valueUsed",("Internally used by DCE to mark an abstract value as used",[Internal])
  478. | Volatile -> ":volatile",("",[Platforms [Java;Cs]])
  479. | Unbound -> ":unbound", ("Compiler internal to denote unbounded global variable",[])
  480. | UnifyMinDynamic -> ":unifyMinDynamic",("Allows a collection of types to unify to Dynamic",[UsedOn TClassField])
  481. | Unreflective -> ":unreflective",("",[Platform Cpp])
  482. | Unsafe -> ":unsafe",("Declares a class, or a method with the C#'s 'unsafe' flag",[Platform Cs; UsedOnEither [TClass;TClassField]])
  483. | Usage -> ":usage",("?",[])
  484. | Used -> ":used",("Internally used by DCE to mark a class or field as used",[Internal])
  485. | Value -> ":value",("Used to store default values for fields and function arguments",[UsedOn TClassField])
  486. | Void -> ":void",("Use Cpp native 'void' return type",[Platform Cpp])
  487. | Last -> assert false
  488. (* do not put any custom metadata after Last *)
  489. | Dollar s -> "$" ^ s,("",[])
  490. | Custom s -> s,("",[])
  491. let hmeta =
  492. let h = Hashtbl.create 0 in
  493. let rec loop i =
  494. let m = Obj.magic i in
  495. if m <> Last then begin
  496. Hashtbl.add h (fst (to_string m)) m;
  497. loop (i + 1);
  498. end;
  499. in
  500. loop 0;
  501. h
  502. let parse s = try Hashtbl.find hmeta (":" ^ s) with Not_found -> Custom (":" ^ s)
  503. let from_string s =
  504. if s = "" then Custom "" else match s.[0] with
  505. | ':' -> (try Hashtbl.find hmeta s with Not_found -> Custom s)
  506. | '$' -> Dollar (String.sub s 1 (String.length s - 1))
  507. | _ -> Custom s
  508. end
  509. let stats =
  510. {
  511. s_files_parsed = ref 0;
  512. s_classes_built = ref 0;
  513. s_methods_typed = ref 0;
  514. s_macros_called = ref 0;
  515. }
  516. let default_config =
  517. {
  518. pf_static = true;
  519. pf_sys = true;
  520. pf_locals_scope = true;
  521. pf_captured_scope = true;
  522. pf_unique_locals = false;
  523. pf_capture_policy = CPNone;
  524. pf_pad_nulls = false;
  525. pf_add_final_return = false;
  526. pf_overload = false;
  527. pf_pattern_matching = false;
  528. pf_can_skip_non_nullable_argument = true;
  529. pf_reserved_type_paths = [];
  530. }
  531. let get_config com =
  532. let defined f = PMap.mem (fst (Define.infos f)) com.defines in
  533. match com.platform with
  534. | Cross ->
  535. default_config
  536. | Js ->
  537. {
  538. pf_static = false;
  539. pf_sys = false;
  540. pf_locals_scope = false;
  541. pf_captured_scope = false;
  542. pf_unique_locals = false;
  543. pf_capture_policy = CPLoopVars;
  544. pf_pad_nulls = false;
  545. pf_add_final_return = false;
  546. pf_overload = false;
  547. pf_pattern_matching = false;
  548. pf_can_skip_non_nullable_argument = true;
  549. pf_reserved_type_paths = [([],"Object");([],"Error")];
  550. }
  551. | Neko ->
  552. {
  553. pf_static = false;
  554. pf_sys = true;
  555. pf_locals_scope = true;
  556. pf_captured_scope = true;
  557. pf_unique_locals = false;
  558. pf_capture_policy = CPNone;
  559. pf_pad_nulls = true;
  560. pf_add_final_return = false;
  561. pf_overload = false;
  562. pf_pattern_matching = false;
  563. pf_can_skip_non_nullable_argument = true;
  564. pf_reserved_type_paths = [];
  565. }
  566. | Flash when defined Define.As3 ->
  567. {
  568. pf_static = true;
  569. pf_sys = false;
  570. pf_locals_scope = false;
  571. pf_captured_scope = true;
  572. pf_unique_locals = true;
  573. pf_capture_policy = CPLoopVars;
  574. pf_pad_nulls = false;
  575. pf_add_final_return = true;
  576. pf_overload = false;
  577. pf_pattern_matching = false;
  578. pf_can_skip_non_nullable_argument = false;
  579. pf_reserved_type_paths = [];
  580. }
  581. | Flash ->
  582. {
  583. pf_static = true;
  584. pf_sys = false;
  585. pf_locals_scope = true;
  586. pf_captured_scope = true; (* handled by genSwf9 *)
  587. pf_unique_locals = false;
  588. pf_capture_policy = CPLoopVars;
  589. pf_pad_nulls = false;
  590. pf_add_final_return = false;
  591. pf_overload = false;
  592. pf_pattern_matching = false;
  593. pf_can_skip_non_nullable_argument = false;
  594. pf_reserved_type_paths = [([],"Object");([],"Error")];
  595. }
  596. | Php ->
  597. {
  598. pf_static = false;
  599. pf_sys = true;
  600. pf_locals_scope = false; (* some duplicate work is done in genPhp *)
  601. pf_captured_scope = false;
  602. pf_unique_locals = false;
  603. pf_capture_policy = CPNone;
  604. pf_pad_nulls = true;
  605. pf_add_final_return = false;
  606. pf_overload = false;
  607. pf_pattern_matching = false;
  608. pf_can_skip_non_nullable_argument = true;
  609. pf_reserved_type_paths = [];
  610. }
  611. | Cpp ->
  612. {
  613. pf_static = true;
  614. pf_sys = true;
  615. pf_locals_scope = true;
  616. pf_captured_scope = true;
  617. pf_unique_locals = false;
  618. pf_capture_policy = CPWrapRef;
  619. pf_pad_nulls = true;
  620. pf_add_final_return = true;
  621. pf_overload = false;
  622. pf_pattern_matching = false;
  623. pf_can_skip_non_nullable_argument = true;
  624. pf_reserved_type_paths = [];
  625. }
  626. | Cs ->
  627. {
  628. pf_static = true;
  629. pf_sys = true;
  630. pf_locals_scope = false;
  631. pf_captured_scope = true;
  632. pf_unique_locals = true;
  633. pf_capture_policy = CPWrapRef;
  634. pf_pad_nulls = true;
  635. pf_add_final_return = false;
  636. pf_overload = true;
  637. pf_pattern_matching = false;
  638. pf_can_skip_non_nullable_argument = true;
  639. pf_reserved_type_paths = [];
  640. }
  641. | Java ->
  642. {
  643. pf_static = true;
  644. pf_sys = true;
  645. pf_locals_scope = false;
  646. pf_captured_scope = true;
  647. pf_unique_locals = false;
  648. pf_capture_policy = CPWrapRef;
  649. pf_pad_nulls = true;
  650. pf_add_final_return = false;
  651. pf_overload = true;
  652. pf_pattern_matching = false;
  653. pf_can_skip_non_nullable_argument = true;
  654. pf_reserved_type_paths = [];
  655. }
  656. | Python ->
  657. {
  658. pf_static = false;
  659. pf_sys = true;
  660. pf_locals_scope = false;
  661. pf_captured_scope = false;
  662. pf_unique_locals = false;
  663. pf_capture_policy = CPLoopVars;
  664. pf_pad_nulls = false;
  665. pf_add_final_return = false;
  666. pf_overload = false;
  667. pf_pattern_matching = false;
  668. pf_can_skip_non_nullable_argument = true;
  669. pf_reserved_type_paths = [];
  670. }
  671. let memory_marker = [|Unix.time()|]
  672. let create v args =
  673. let m = Type.mk_mono() in
  674. let defines =
  675. PMap.add "true" "1" (
  676. PMap.add "source-header" "Generated by Haxe" (
  677. if !display_default <> DMNone then PMap.add "display" "1" PMap.empty else PMap.empty))
  678. in
  679. {
  680. version = v;
  681. args = args;
  682. sys_args = args;
  683. debug = false;
  684. display = !display_default;
  685. verbose = false;
  686. foptimize = true;
  687. features = Hashtbl.create 0;
  688. platform = Cross;
  689. config = default_config;
  690. print = (fun s -> print_string s; flush stdout);
  691. run_command = Sys.command;
  692. std_path = [];
  693. class_path = [];
  694. main_class = None;
  695. defines = defines;
  696. package_rules = PMap.empty;
  697. file = "";
  698. types = [];
  699. filters = [];
  700. final_filters = [];
  701. modules = [];
  702. main = None;
  703. flash_version = 10.;
  704. resources = Hashtbl.create 0;
  705. php_front = None;
  706. php_lib = None;
  707. swf_libs = [];
  708. java_libs = [];
  709. net_libs = [];
  710. net_std = [];
  711. net_path_map = Hashtbl.create 0;
  712. c_args = [];
  713. neko_libs = [];
  714. include_files = [];
  715. php_prefix = None;
  716. js_gen = None;
  717. load_extern_type = [];
  718. defines_signature = None;
  719. get_macros = (fun() -> None);
  720. warning = (fun _ _ -> assert false);
  721. error = (fun _ _ -> assert false);
  722. basic = {
  723. tvoid = m;
  724. tint = m;
  725. tfloat = m;
  726. tbool = m;
  727. tnull = (fun _ -> assert false);
  728. tstring = m;
  729. tarray = (fun _ -> assert false);
  730. };
  731. file_lookup_cache = Hashtbl.create 0;
  732. stored_typed_exprs = PMap.empty;
  733. memory_marker = memory_marker;
  734. parser_cache = Hashtbl.create 0;
  735. }
  736. let log com str =
  737. if com.verbose then com.print (str ^ "\n")
  738. let clone com =
  739. let t = com.basic in
  740. { com with
  741. basic = { t with tvoid = t.tvoid };
  742. main_class = None;
  743. features = Hashtbl.create 0;
  744. file_lookup_cache = Hashtbl.create 0;
  745. }
  746. let file_time file =
  747. try (Unix.stat file).Unix.st_mtime with _ -> 0.
  748. let get_signature com =
  749. match com.defines_signature with
  750. | Some s -> s
  751. | None ->
  752. let str = String.concat "@" (PMap.foldi (fun k v acc ->
  753. (* don't make much difference between these special compilation flags *)
  754. match k with
  755. | "display" | "use_rtti_doc" | "macrotimes" -> acc
  756. | _ -> k :: v :: acc
  757. ) com.defines []) in
  758. let s = Digest.string str in
  759. com.defines_signature <- Some s;
  760. s
  761. let file_extension file =
  762. match List.rev (ExtString.String.nsplit file ".") with
  763. | e :: _ -> String.lowercase e
  764. | [] -> ""
  765. let platforms = [
  766. Js;
  767. Neko;
  768. Flash;
  769. Php;
  770. Cpp;
  771. Cs;
  772. Java;
  773. Python;
  774. ]
  775. let platform_name = function
  776. | Cross -> "cross"
  777. | Js -> "js"
  778. | Neko -> "neko"
  779. | Flash -> "flash"
  780. | Php -> "php"
  781. | Cpp -> "cpp"
  782. | Cs -> "cs"
  783. | Java -> "java"
  784. | Python -> "python"
  785. let flash_versions = List.map (fun v ->
  786. let maj = int_of_float v in
  787. let min = int_of_float (mod_float (v *. 10.) 10.) in
  788. v, string_of_int maj ^ (if min = 0 then "" else "_" ^ string_of_int min)
  789. ) [9.;10.;10.1;10.2;10.3;11.;11.1;11.2;11.3;11.4;11.5;11.6;11.7;11.8;11.9;12.0;13.0;14.0;15.0;16.0;17.0]
  790. let flash_version_tag = function
  791. | 6. -> 6
  792. | 7. -> 7
  793. | 8. -> 8
  794. | 9. -> 9
  795. | 10. | 10.1 -> 10
  796. | 10.2 -> 11
  797. | 10.3 -> 12
  798. | 11. -> 13
  799. | 11.1 -> 14
  800. | 11.2 -> 15
  801. | 11.3 -> 16
  802. | 11.4 -> 17
  803. | 11.5 -> 18
  804. | 11.6 -> 19
  805. | 11.7 -> 20
  806. | 11.8 -> 21
  807. | 11.9 -> 22
  808. | 12.0 -> 23
  809. | 13.0 -> 24
  810. | 14.0 -> 25
  811. | 15.0 -> 26
  812. | 16.0 -> 27
  813. | 17.0 -> 28
  814. | v -> failwith ("Invalid SWF version " ^ string_of_float v)
  815. let raw_defined ctx v =
  816. PMap.mem v ctx.defines
  817. let defined ctx v =
  818. raw_defined ctx (fst (Define.infos v))
  819. let raw_defined_value ctx k =
  820. PMap.find k ctx.defines
  821. let defined_value ctx v =
  822. raw_defined_value ctx (fst (Define.infos v))
  823. let defined_value_safe ctx v =
  824. try defined_value ctx v
  825. with Not_found -> ""
  826. let raw_define ctx v =
  827. let k,v = try ExtString.String.split v "=" with _ -> v,"1" in
  828. ctx.defines <- PMap.add k v ctx.defines;
  829. let k = String.concat "_" (ExtString.String.nsplit k "-") in
  830. ctx.defines <- PMap.add k v ctx.defines;
  831. ctx.defines_signature <- None
  832. let define_value ctx k v =
  833. raw_define ctx (fst (Define.infos k) ^ "=" ^ v)
  834. let define ctx v =
  835. raw_define ctx (fst (Define.infos v))
  836. let init_platform com pf =
  837. com.platform <- pf;
  838. let name = platform_name pf in
  839. let forbid acc p = if p = name || PMap.mem p acc then acc else PMap.add p Forbidden acc in
  840. com.package_rules <- List.fold_left forbid com.package_rules (List.map platform_name platforms);
  841. com.config <- get_config com;
  842. (* if com.config.pf_static then define com "static"; *)
  843. if com.config.pf_sys then define com Define.Sys else com.package_rules <- PMap.add "sys" Forbidden com.package_rules;
  844. raw_define com name
  845. let add_feature com f =
  846. Hashtbl.replace com.features f true
  847. let has_dce com =
  848. (try defined_value com Define.Dce <> "no" with Not_found -> false)
  849. (*
  850. TODO: The has_dce check is there because we mark types with @:directlyUsed in the DCE filter,
  851. which is not run in dce=no and thus we can't know if a type is used directly or not,
  852. so we just assume that they are.
  853. If we had dce filter always running (even with dce=no), we would have types marked with @:directlyUsed
  854. and we wouldn't need to generate unnecessary imports in dce=no, but that's good enough for now.
  855. *)
  856. let is_directly_used com meta =
  857. not (has_dce com) || Ast.Meta.has Ast.Meta.DirectlyUsed meta
  858. let rec has_feature com f =
  859. try
  860. Hashtbl.find com.features f
  861. with Not_found ->
  862. if com.types = [] then not (has_dce com) else
  863. match List.rev (ExtString.String.nsplit f ".") with
  864. | [] -> assert false
  865. | [cl] -> has_feature com (cl ^ ".*")
  866. | meth :: cl :: pack ->
  867. let r = (try
  868. let path = List.rev pack, cl in
  869. (match List.find (fun t -> t_path t = path && not (Ast.Meta.has Ast.Meta.RealPath (t_infos t).mt_meta)) com.types with
  870. | t when meth = "*" -> (match t with TAbstractDecl a -> Ast.Meta.has Ast.Meta.ValueUsed a.a_meta | _ ->
  871. Ast.Meta.has Ast.Meta.Used (t_infos t).mt_meta)
  872. | TClassDecl ({cl_extern = true} as c) when com.platform <> Js || cl <> "Array" && cl <> "Math" ->
  873. Meta.has Meta.Used (try PMap.find meth c.cl_statics with Not_found -> PMap.find meth c.cl_fields).cf_meta
  874. | TClassDecl c ->
  875. PMap.exists meth c.cl_statics || PMap.exists meth c.cl_fields
  876. | _ ->
  877. false)
  878. with Not_found ->
  879. false
  880. ) in
  881. let r = r || not (has_dce com) in
  882. Hashtbl.add com.features f r;
  883. r
  884. let allow_package ctx s =
  885. try
  886. if (PMap.find s ctx.package_rules) = Forbidden then ctx.package_rules <- PMap.remove s ctx.package_rules
  887. with Not_found ->
  888. ()
  889. let error msg p = raise (Abort (msg,p))
  890. let platform ctx p = ctx.platform = p
  891. let add_filter ctx f =
  892. ctx.filters <- f :: ctx.filters
  893. let add_final_filter ctx f =
  894. ctx.final_filters <- f :: ctx.final_filters
  895. let find_file ctx f =
  896. try
  897. (match Hashtbl.find ctx.file_lookup_cache f with
  898. | None -> raise Exit
  899. | Some f -> f)
  900. with Exit ->
  901. raise Not_found
  902. | Not_found ->
  903. let rec loop had_empty = function
  904. | [] when had_empty -> raise Not_found
  905. | [] -> loop true [""]
  906. | p :: l ->
  907. let file = p ^ f in
  908. if Sys.file_exists file then
  909. file
  910. else
  911. loop (had_empty || p = "") l
  912. in
  913. let r = (try Some (loop false ctx.class_path) with Not_found -> None) in
  914. Hashtbl.add ctx.file_lookup_cache f r;
  915. (match r with
  916. | None -> raise Not_found
  917. | Some f -> f)
  918. let get_full_path f = try Extc.get_full_path f with _ -> f
  919. let unique_full_path = if Sys.os_type = "Win32" || Sys.os_type = "Cygwin" then (fun f -> String.lowercase (get_full_path f)) else get_full_path
  920. let get_path_parts f =
  921. let f = String.concat "/" (ExtString.String.nsplit f "\\") in
  922. let cl = ExtString.String.nsplit f "." in
  923. let cl = (match List.rev cl with
  924. | ["hx";path] -> ExtString.String.nsplit path "/"
  925. | _ -> cl
  926. ) in
  927. cl
  928. let normalize_path p =
  929. let l = String.length p in
  930. if l = 0 then
  931. "./"
  932. else match p.[l-1] with
  933. | '\\' | '/' -> p
  934. | _ -> p ^ "/"
  935. let rec mkdir_recursive base dir_list =
  936. match dir_list with
  937. | [] -> ()
  938. | dir :: remaining ->
  939. let path = match base with
  940. | "" -> dir
  941. | "/" -> "/" ^ dir
  942. | _ -> base ^ "/" ^ dir
  943. in
  944. if not ( (path = "") || ( ((String.length path) = 2) && ((String.sub path 1 1) = ":") ) ) then
  945. if not (Sys.file_exists path) then
  946. Unix.mkdir path 0o755;
  947. mkdir_recursive (if (path = "") then "/" else path) remaining
  948. let mkdir_from_path path =
  949. let parts = Str.split_delim (Str.regexp "[\\/]+") path in
  950. match parts with
  951. | [] -> (* path was "" *) ()
  952. | _ ->
  953. let dir_list = List.rev (List.tl (List.rev parts)) in
  954. mkdir_recursive "" dir_list
  955. let mem_size v =
  956. Objsize.size_with_headers (Objsize.objsize v [] [])
  957. (* ------------------------- TIMERS ----------------------------- *)
  958. type timer_infos = {
  959. name : string;
  960. mutable start : float list;
  961. mutable total : float;
  962. }
  963. let get_time = Extc.time
  964. let htimers = Hashtbl.create 0
  965. let new_timer name =
  966. try
  967. let t = Hashtbl.find htimers name in
  968. t.start <- get_time() :: t.start;
  969. t
  970. with Not_found ->
  971. let t = { name = name; start = [get_time()]; total = 0.; } in
  972. Hashtbl.add htimers name t;
  973. t
  974. let curtime = ref []
  975. let close t =
  976. let start = (match t.start with
  977. | [] -> assert false
  978. | s :: l -> t.start <- l; s
  979. ) in
  980. let now = get_time() in
  981. let dt = now -. start in
  982. t.total <- t.total +. dt;
  983. let rec loop() =
  984. match !curtime with
  985. | [] -> failwith ("Timer " ^ t.name ^ " closed while not active")
  986. | tt :: l -> curtime := l; if t != tt then loop()
  987. in
  988. loop();
  989. (* because of rounding errors while adding small times, we need to make sure that we don't have start > now *)
  990. List.iter (fun ct -> ct.start <- List.map (fun t -> let s = t +. dt in if s > now then now else s) ct.start) !curtime
  991. let timer name =
  992. let t = new_timer name in
  993. curtime := t :: !curtime;
  994. (function() -> close t)
  995. let rec close_times() =
  996. match !curtime with
  997. | [] -> ()
  998. | t :: _ -> close t; close_times()
  999. ;;
  1000. Ast.Meta.to_string_ref := fun m -> fst (MetaInfo.to_string m)
  1001. (* Taken from OCaml source typing/oprint.ml
  1002. This is a better version of string_of_float which prints without loss of precision
  1003. so that float_of_string (float_repres x) = x for all floats x
  1004. *)
  1005. let valid_float_lexeme s =
  1006. let l = String.length s in
  1007. let rec loop i =
  1008. if i >= l then s ^ "." else
  1009. match s.[i] with
  1010. | '0' .. '9' | '-' -> loop (i+1)
  1011. | _ -> s
  1012. in loop 0
  1013. let float_repres f =
  1014. match classify_float f with
  1015. | FP_nan -> "nan"
  1016. | FP_infinite ->
  1017. if f < 0.0 then "neg_infinity" else "infinity"
  1018. | _ ->
  1019. let float_val =
  1020. let s1 = Printf.sprintf "%.12g" f in
  1021. if f = float_of_string s1 then s1 else
  1022. let s2 = Printf.sprintf "%.15g" f in
  1023. if f = float_of_string s2 then s2 else
  1024. Printf.sprintf "%.18g" f
  1025. in valid_float_lexeme float_val