common.ml 45 KB

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