2
0

common.ml 46 KB

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