common.ml 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. | Fdb
  174. | FileExtension
  175. | FlashStrict
  176. | FlashUseStage
  177. | ForceNativeProperty
  178. | FormatWarning
  179. | GencommonDebug
  180. | HaxeBoot
  181. | HaxeVer
  182. | HxcppApiLevel
  183. | IncludePrefix
  184. | Interp
  185. | JavaVer
  186. | JsClassic
  187. | JsEs5
  188. | JsFlatten
  189. | KeepOldOutput
  190. | LoopUnrollMaxCost
  191. | Macro
  192. | MacroTimes
  193. | NekoSource
  194. | NekoV1
  195. | NetworkSandbox
  196. | NetVer
  197. | NetTarget
  198. | NoCompilation
  199. | NoCOpt
  200. | NoDeprecationWarnings
  201. | NoFlashOverride
  202. | NoDebug
  203. | NoInline
  204. | NoOpt
  205. | NoPatternMatching
  206. | NoRoot
  207. | NoSimplify
  208. | NoSwfCompress
  209. | NoTraces
  210. | PhpPrefix
  211. | RealPosition
  212. | ReplaceFiles
  213. | Scriptable
  214. | ShallowExpose
  215. | SourceMapContent
  216. | Swc
  217. | SwfCompressLevel
  218. | SwfDebugPassword
  219. | SwfDirectBlit
  220. | SwfGpu
  221. | SwfMark
  222. | SwfMetadata
  223. | SwfPreloaderFrame
  224. | SwfProtected
  225. | SwfScriptTimeout
  226. | SwfUseDoAbc
  227. | Sys
  228. | UnityStdTarget
  229. | Unity46LineNumbers
  230. | Unsafe
  231. | UseNekoc
  232. | UseRttiDoc
  233. | Vcproj
  234. | NoMacroCache
  235. | Last (* must be last *)
  236. let infos = function
  237. | AbsolutePath -> ("absolute_path","Print absolute file path in trace output")
  238. | AdvancedTelemetry -> ("advanced-telemetry","Allow the SWF to be measured with Monocle tool")
  239. | Analyzer -> ("analyzer","Use static analyzer for optimization (experimental)")
  240. | As3 -> ("as3","Defined when outputing flash9 as3 source code")
  241. | CheckXmlProxy -> ("check_xml_proxy","Check the used fields of the xml proxy")
  242. | CoreApi -> ("core_api","Defined in the core api context")
  243. | CoreApiSerialize -> ("core_api_serialize","Sets so some generated core api classes be marked with the Serializable attribute on C#")
  244. | Cppia -> ("cppia", "Generate experimental cpp instruction assembly")
  245. | Dce -> ("dce","The current DCE mode")
  246. | DceDebug -> ("dce_debug","Show DCE log")
  247. | Debug -> ("debug","Activated when compiling with -debug")
  248. | Display -> ("display","Activated during completion")
  249. | DllExport -> ("dll_export", "GenCPP experimental linking")
  250. | DllImport -> ("dll_import", "GenCPP experimental linking")
  251. | DocGen -> ("doc_gen","Do not perform any removal/change in order to correctly generate documentation")
  252. | Dump -> ("dump","Dump the complete typed AST for internal debugging")
  253. | DumpDependencies -> ("dump_dependencies","Dump the classes dependencies")
  254. | DumpIgnoreVarIds -> ("dump_ignore_var_ids","Dump files do not contain variable IDs (helps with diff)")
  255. | Fdb -> ("fdb","Enable full flash debug infos for FDB interactive debugging")
  256. | FileExtension -> ("file_extension","Output filename extension for cpp source code")
  257. | FlashStrict -> ("flash_strict","More strict typing for flash target")
  258. | FlashUseStage -> ("flash_use_stage","Keep the SWF library initial stage")
  259. | ForceNativeProperty -> ("force_native_property","Tag all properties with :nativeProperty metadata for 3.1 compatibility")
  260. | FormatWarning -> ("format_warning","Print a warning for each formated string, for 2.x compatibility")
  261. | GencommonDebug -> ("gencommon_debug","GenCommon internal")
  262. | HaxeBoot -> ("haxe_boot","Given the name 'haxe' to the flash boot class instead of a generated name")
  263. | HaxeVer -> ("haxe_ver","The current Haxe version value")
  264. | HxcppApiLevel -> ("hxcpp_api_level","Provided to allow compatibility between hxcpp versions")
  265. | IncludePrefix -> ("include_prefix","prepend path to generated include files")
  266. | Interp -> ("interp","The code is compiled to be run with --interp")
  267. | JavaVer -> ("java_ver", "<version:5-7> Sets the Java version to be targeted")
  268. | JsClassic -> ("js_classic","Don't use a function wrapper and strict mode in JS output")
  269. | JsEs5 -> ("js_es5","Generate JS for ES5-compliant runtimes")
  270. | JsFlatten -> ("js_flatten","Generate classes to use fewer object property lookups")
  271. | KeepOldOutput -> ("keep_old_output","Keep old source files in the output directory (for C#/Java)")
  272. | LoopUnrollMaxCost -> ("loop_unroll_max_cost","Maximum cost (number of expressions * iterations) before loop unrolling is canceled (default 250)")
  273. | Macro -> ("macro","Defined when we compile code in the macro context")
  274. | MacroTimes -> ("macro_times","Display per-macro timing when used with --times")
  275. | NetVer -> ("net_ver", "<version:20-45> Sets the .NET version to be targeted")
  276. | NetTarget -> ("net_target", "<name> Sets the .NET target. Defaults to \"net\". xbox, micro (Micro Framework), compact (Compact Framework) are some valid values")
  277. | NekoSource -> ("neko_source","Output neko source instead of bytecode")
  278. | NekoV1 -> ("neko_v1","Keep Neko 1.x compatibility")
  279. | NetworkSandbox -> ("network-sandbox","Use local network sandbox instead of local file access one")
  280. | NoCompilation -> ("no-compilation","Disable final compilation for Cs, Cpp and Java")
  281. | NoCOpt -> ("no_copt","Disable completion optimization (for debug purposes)")
  282. | NoDebug -> ("no_debug","Remove all debug macros from cpp output")
  283. | NoDeprecationWarnings -> ("no-deprecation-warnings","Do not warn if fields annotated with @:deprecated are used")
  284. | NoFlashOverride -> ("no-flash-override", "Change overrides on some basic classes into HX suffixed methods, flash only")
  285. | NoOpt -> ("no_opt","Disable optimizations")
  286. | NoPatternMatching -> ("no_pattern_matching","Disable pattern matching")
  287. | NoInline -> ("no_inline","Disable inlining")
  288. | NoRoot -> ("no_root","Generate top-level types into haxe.root namespace")
  289. | NoMacroCache -> ("no_macro_cache","Disable macro context caching")
  290. | NoSimplify -> "no_simplify",("Disable simplification filter")
  291. | NoSwfCompress -> ("no_swf_compress","Disable SWF output compression")
  292. | NoTraces -> ("no_traces","Disable all trace calls")
  293. | PhpPrefix -> ("php_prefix","Compiled with --php-prefix")
  294. | RealPosition -> ("real_position","Disables haxe source mapping when targetting C#")
  295. | ReplaceFiles -> ("replace_files","GenCommon internal")
  296. | Scriptable -> ("scriptable","GenCPP internal")
  297. | ShallowExpose -> ("shallow-expose","Expose types to surrounding scope of Haxe generated closure without writing to window object")
  298. | SourceMapContent -> ("source-map-content","Include the hx sources as part of the JS source map")
  299. | Swc -> ("swc","Output a SWC instead of a SWF")
  300. | SwfCompressLevel -> ("swf_compress_level","<level:1-9> Set the amount of compression for the SWF output")
  301. | SwfDebugPassword -> ("swf_debug_password", "Set a password for debugging.")
  302. | SwfDirectBlit -> ("swf_direct_blit", "Use hardware acceleration to blit graphics")
  303. | SwfGpu -> ("swf_gpu", "Use GPU compositing features when drawing graphics")
  304. | SwfMark -> ("swf_mark","GenSWF8 internal")
  305. | SwfMetadata -> ("swf_metadata", "=<file> Include contents of <file> as metadata in the swf.")
  306. | SwfPreloaderFrame -> ("swf_preloader_frame", "Insert empty first frame in swf")
  307. | SwfProtected -> ("swf_protected","Compile Haxe private as protected in the SWF instead of public")
  308. | SwfScriptTimeout -> ("swf_script_timeout", "Maximum ActionScript processing time before script stuck dialog box displays (in seconds)")
  309. | SwfUseDoAbc -> ("swf_use_doabc", "Use DoAbc swf-tag instead of DoAbcDefine")
  310. | Sys -> ("sys","Defined for all system platforms")
  311. | 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")
  312. (* see https://github.com/HaxeFoundation/haxe/issues/3759 *)
  313. | Unity46LineNumbers -> ("unity46_line_numbers", "Fixes line numbers in generated C# files for Unity 4.6 Mono compiler")
  314. | Unsafe -> ("unsafe","Allow unsafe code when targeting C#")
  315. | UseNekoc -> ("use_nekoc","Use nekoc compiler instead of internal one")
  316. | UseRttiDoc -> ("use_rtti_doc","Allows access to documentation during compilation")
  317. | Vcproj -> ("vcproj","GenCPP internal")
  318. | Last -> assert false
  319. end
  320. module MetaInfo = struct
  321. open Meta
  322. type meta_usage =
  323. | TClass
  324. | TClassField
  325. | TAbstract
  326. | TAbstractField
  327. | TEnum
  328. | TTypedef
  329. | TAnyField
  330. | TExpr
  331. type meta_parameter =
  332. | HasParam of string
  333. | Platform of platform
  334. | Platforms of platform list
  335. | UsedOn of meta_usage
  336. | UsedOnEither of meta_usage list
  337. | Internal
  338. let to_string = function
  339. | Abstract -> ":abstract",("Sets the underlying class implementation as 'abstract'",[Platforms [Java;Cs]])
  340. | Access -> ":access",("Forces private access to package, type or field",[HasParam "Target path";UsedOnEither [TClass;TClassField]])
  341. | Accessor -> ":accessor",("Used internally by DCE to mark property accessors",[UsedOn TClassField;Internal])
  342. | Allow -> ":allow",("Allows private access from package, type or field",[HasParam "Target path";UsedOnEither [TClass;TClassField]])
  343. | Analyzer -> ":analyzer",("Used to configure the static analyzer",[])
  344. | 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])
  345. | ArrayAccess -> ":arrayAccess",("Allows [] access on an abstract",[UsedOnEither [TAbstract;TAbstractField]])
  346. | Ast -> ":ast",("Internally used to pass the AST source into the typed AST",[Internal])
  347. | AutoBuild -> ":autoBuild",("Extends @:build metadata to all extending and implementing classes",[HasParam "Build macro call";UsedOn TClass])
  348. | Bind -> ":bind",("Override Swf class declaration",[Platform Flash;UsedOn TClass])
  349. | Bitmap -> ":bitmap",("Embeds given bitmap data into the class (must extend flash.display.BitmapData)",[HasParam "Bitmap file path";UsedOn TClass;Platform Flash])
  350. | BridgeProperties -> ":bridgeProperties",("Creates native property bridges for all Haxe properties in this class.",[UsedOn TClass;Platform Cs])
  351. | Build -> ":build",("Builds a class or enum from a macro",[HasParam "Build macro call";UsedOnEither [TClass;TEnum]])
  352. | BuildXml -> ":buildXml",("",[Platform Cpp])
  353. | Callable -> ":callable",("Abstract forwards call to its underlying type",[UsedOn TAbstract])
  354. | Class -> ":class",("Used internally to annotate an enum that will be generated as a class",[Platforms [Java;Cs]; UsedOn TEnum; Internal])
  355. | ClassCode -> ":classCode",("Used to inject platform-native code into a class",[Platforms [Java;Cs]; UsedOn TClass])
  356. | Commutative -> ":commutative",("Declares an abstract operator as commutative",[UsedOn TAbstractField])
  357. | CompilerGenerated -> ":compilerGenerated",("Marks a field as generated by the compiler. Shouldn't be used by the end user",[Platforms [Java;Cs]])
  358. | CoreApi -> ":coreApi",("Identifies this class as a core api class (forces Api check)",[UsedOnEither [TClass;TEnum;TTypedef;TAbstract]])
  359. | CoreType -> ":coreType",("Identifies an abstract as core type so that it requires no implementation",[UsedOn TAbstract])
  360. | CppFileCode -> ":cppFileCode",("",[Platform Cpp])
  361. | CppNamespaceCode -> ":cppNamespaceCode",("",[Platform Cpp])
  362. | CsNative -> ":csNative",("Automatically added by -net-lib on classes generated from .NET DLL files",[Platform Cs; UsedOnEither[TClass;TEnum]; Internal])
  363. | Dce -> ":dce",("Forces dead code elimination even when -dce full is not specified",[UsedOnEither [TClass;TEnum]])
  364. | Debug -> ":debug",("Forces debug information to be generated into the Swf even without -debug",[UsedOnEither [TClass;TClassField]; Platform Flash])
  365. | Decl -> ":decl",("",[Platform Cpp])
  366. | DefParam -> ":defParam",("?",[])
  367. | Delegate -> ":delegate",("Automatically added by -net-lib on delegates",[Platform Cs; UsedOn TAbstract])
  368. | Depend -> ":depend",("",[Platform Cpp])
  369. | 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]])
  370. | DirectlyUsed -> ":directlyUsed",("Marks types that are directly referenced by non-extern code",[Internal])
  371. | DynamicObject -> ":dynamicObject",("Used internally to identify the Dynamic Object implementation",[Platforms [Java;Cs]; UsedOn TClass; Internal])
  372. | Enum -> ":enum",("Used internally to annotate a class that was generated from an enum",[Platforms [Java;Cs]; UsedOn TClass; Internal])
  373. | EnumConstructorParam -> ":enumConstructorParam",("Used internally to annotate GADT type parameters",[UsedOn TClass; Internal])
  374. | Event -> ":event",("Automatically added by -net-lib on events. Has no effect on types compiled by Haxe.",[Platform Cs; UsedOn TClassField])
  375. | Exhaustive -> ":exhaustive",("",[Internal])
  376. | Expose -> ":expose",("Makes the class available on the window object",[HasParam "?Name=Class path";UsedOn TClass;Platform Js])
  377. | Extern -> ":extern",("Marks the field as extern so it is not generated",[UsedOn TClassField])
  378. | FakeEnum -> ":fakeEnum",("Treat enum as collection of values of the specified type",[HasParam "Type name";UsedOn TEnum])
  379. | 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])
  380. | Final -> ":final",("Prevents a class from being extended",[UsedOn TClass])
  381. | FlatEnum -> ":flatEnum",("Internally used to mark an enum as being flat, i.e. having no function constructors",[UsedOn TEnum; Internal])
  382. | Font -> ":font",("Embeds the given TrueType font into the class (must extend flash.text.Font)",[HasParam "TTF path";HasParam "Range String";UsedOn TClass])
  383. | Forward -> ":forward",("Forwards field access to underlying type",[HasParam "List of field names";UsedOn TAbstract])
  384. | From -> ":from",("Specifies that the field of the abstract is a cast operation from the type identified in the function",[UsedOn TAbstractField])
  385. | FunctionCode -> ":functionCode",("",[Platform Cpp])
  386. | FunctionTailCode -> ":functionTailCode",("",[Platform Cpp])
  387. | Generic -> ":generic",("Marks a class or class field as generic so each type parameter combination generates its own type/field",[UsedOnEither [TClass;TClassField]])
  388. | GenericBuild -> ":genericBuild",("Builds instances of a type using the specified macro",[UsedOn TClass])
  389. | GenericInstance -> ":genericInstance",("Internally used to mark instances of @:generic methods",[UsedOn TClassField;Internal])
  390. | Getter -> ":getter",("Generates a native getter function on the given field",[HasParam "Class field name";UsedOn TClassField;Platform Flash])
  391. | Hack -> ":hack",("Allows extending classes marked as @:final",[UsedOn TClass])
  392. | HasUntyped -> (":has_untyped",("Used by the typer to mark fields that have untyped expressions",[Internal]))
  393. | HaxeGeneric -> ":haxeGeneric",("Used internally to annotate non-native generic classes",[Platform Cs; UsedOnEither[TClass;TEnum]; Internal])
  394. | HeaderClassCode -> ":headerClassCode",("",[Platform Cpp])
  395. | HeaderCode -> ":headerCode",("",[Platform Cpp])
  396. | HeaderNamespaceCode -> ":headerNamespaceCode",("",[Platform Cpp])
  397. | HxGen -> ":hxGen",("Annotates that an extern class was generated by Haxe",[Platforms [Java;Cs]; UsedOnEither [TClass;TEnum]])
  398. | IfFeature -> ":ifFeature",("Causes a field to be kept by DCE if the given feature is part of the compilation",[HasParam "Feature name";UsedOn TClassField])
  399. | Impl -> ":impl",("Used internally to mark abstract implementation fields",[UsedOn TAbstractField; Internal])
  400. | PythonImport -> ":pythonImport",("Generates python import statement for extern classes",[Platforms [Python]; UsedOn TClass])
  401. | ImplicitCast -> ":implicitCast",("Generated automatically on the AST when an implicit abstract cast happens",[Internal; UsedOn TExpr])
  402. | Include -> ":include",("",[Platform Cpp])
  403. | InitPackage -> ":initPackage",("?",[])
  404. | Meta.Internal -> ":internal",("Generates the annotated field/class with 'internal' access",[Platforms [Java;Cs]; UsedOnEither[TClass;TEnum;TClassField]])
  405. | IsVar -> ":isVar",("Forces a physical field to be generated for properties that otherwise would not require one",[UsedOn TClassField])
  406. | 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])
  407. | JavaNative -> ":javaNative",("Automatically added by -java-lib on classes generated from JAR/class files",[Platform Java; UsedOnEither[TClass;TEnum]; Internal])
  408. | JsRequire -> ":jsRequire",("Generate javascript module require expression for given extern",[Platform Js; UsedOn TClass])
  409. | Keep -> ":keep",("Causes a field or type to be kept by DCE",[])
  410. | KeepInit -> ":keepInit",("Causes a class to be kept by DCE even if all its field are removed",[UsedOn TClass])
  411. | KeepSub -> ":keepSub",("Extends @:keep metadata to all implementing and extending classes",[UsedOn TClass])
  412. | Meta -> ":meta",("Internally used to mark a class field as being the metadata field",[])
  413. | Macro -> ":macro",("(deprecated)",[])
  414. | MaybeUsed -> ":maybeUsed",("Internally used by DCE to mark fields that might be kept",[Internal])
  415. | MergeBlock -> ":mergeBlock",("Merge the annotated block into the current scope",[UsedOn TExpr])
  416. | MultiType -> ":multiType",("Specifies that an abstract chooses its this-type from its @:to functions",[UsedOn TAbstract; HasParam "Relevant type parameters"])
  417. | Native -> ":native",("Rewrites the path of a class or enum during generation",[HasParam "Output type path";UsedOnEither [TClass;TEnum]])
  418. | 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])
  419. | 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]])
  420. | NativeGeneric -> ":nativeGeneric",("Used internally to annotate native generic classes",[Platform Cs; UsedOnEither[TClass;TEnum]; Internal])
  421. | NativeProperty -> ":nativeProperty",("Use native properties which will execute even with dynamic usage",[Platform Cpp])
  422. | NoCompletion -> ":noCompletion",("Prevents the compiler from suggesting completion on this field",[UsedOn TClassField])
  423. | NoDebug -> ":noDebug",("Does not generate debug information into the Swf even if -debug is set",[UsedOnEither [TClass;TClassField];Platform Flash])
  424. | NoDoc -> ":noDoc",("Prevents a type from being included in documentation generation",[])
  425. | NoExpr -> ":noExpr",("Internally used to mark abstract fields which have no expression by design",[Internal])
  426. | NoImportGlobal -> ":noImportGlobal",("Prevents a static field from being imported with import Class.*",[UsedOn TAnyField])
  427. | NoPackageRestrict -> ":noPackageRestrict",("Allows a module to be accessed across all targets if found on its first type.",[Internal])
  428. | NoStack -> ":noStack",("",[Platform Cpp])
  429. | NotNull -> ":notNull",("Declares an abstract type as not accepting null values",[UsedOn TAbstract])
  430. | NoUsing -> ":noUsing",("Prevents a field from being used with 'using'",[UsedOn TClassField])
  431. | Ns -> ":ns",("Internally used by the Swf generator to handle namespaces",[Platform Flash])
  432. | Op -> ":op",("Declares an abstract field as being an operator overload",[HasParam "The operation";UsedOn TAbstractField])
  433. | Optional -> ":optional",("Marks the field of a structure as optional",[UsedOn TClassField])
  434. | Overload -> ":overload",("Allows the field to be called with different argument types",[HasParam "Function specification (no expression)";UsedOn TClassField])
  435. | Public -> ":public",("Marks a class field as being public",[UsedOn TClassField])
  436. | PublicFields -> ":publicFields",("Forces all class fields of inheriting classes to be public",[UsedOn TClass])
  437. | QuotedField -> ":quotedField",("Used internally to mark structure fields which are quoted in syntax",[Internal])
  438. | PrivateAccess -> ":privateAccess",("Allow private access to anything for the annotated expression",[UsedOn TExpr])
  439. | Protected -> ":protected",("Marks a class field as being protected",[UsedOn TClassField])
  440. | Property -> ":property",("Marks a property field to be compiled as a native C# property",[UsedOn TClassField;Platform Cs])
  441. | ReadOnly -> ":readOnly",("Generates a field with the 'readonly' native keyword",[Platform Cs; UsedOn TClassField])
  442. | RealPath -> ":realPath",("Internally used on @:native types to retain original path information",[Internal])
  443. | Remove -> ":remove",("Causes an interface to be removed from all implementing classes before generation",[UsedOn TClass])
  444. | Require -> ":require",("Allows access to a field only if the specified compiler flag is set",[HasParam "Compiler flag to check";UsedOn TClassField])
  445. | RequiresAssign -> ":requiresAssign",("Used internally to mark certain abstract operator overloads",[Internal])
  446. (* | Resolve -> ":resolve",("Abstract fields marked with this metadata can be used to resolve unknown fields",[UsedOn TClassField]) *)
  447. | ReplaceReflection -> ":replaceReflection",("Used internally to specify a function that should replace its internal __hx_functionName counterpart",[Platforms [Java;Cs]; UsedOnEither[TClass;TEnum]; Internal])
  448. | Rtti -> ":rtti",("Adds runtime type informations",[UsedOn TClass])
  449. | Runtime -> ":runtime",("?",[])
  450. | RuntimeValue -> ":runtimeValue",("Marks an abstract as being a runtime value",[UsedOn TAbstract])
  451. | SelfCall -> ":selfCall",("Translates method calls into calling object directly",[UsedOn TClassField; Platform Js])
  452. | Setter -> ":setter",("Generates a native getter function on the given field",[HasParam "Class field name";UsedOn TClassField;Platform Flash])
  453. | StoredTypedExpr -> ":storedTypedExpr",("Used internally to reference a typed expression returned from a macro",[Internal])
  454. | SkipCtor -> ":skipCtor",("Used internally to generate a constructor as if it were a native type (no __hx_ctor)",[Platforms [Java;Cs]; Internal])
  455. | SkipReflection -> ":skipReflection",("Used internally to annotate a field that shouldn't have its reflection data generated",[Platforms [Java;Cs]; UsedOn TClassField; Internal])
  456. | 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])
  457. | Struct -> ":struct",("Marks a class definition as a struct.",[Platform Cs; UsedOn TClass])
  458. | StructAccess -> ":structAccess",("Marks an extern class as using struct access('.') not pointer('->').",[Platform Cpp; UsedOn TClass])
  459. | SuppressWarnings -> ":suppressWarnings",("Adds a SuppressWarnings annotation for the generated Java class",[Platform Java; UsedOn TClass])
  460. | Throws -> ":throws",("Adds a 'throws' declaration to the generated function.",[HasParam "Type as String"; Platform Java; UsedOn TClassField])
  461. | This -> ":this",("Internally used to pass a 'this' expression to macros",[Internal; UsedOn TExpr])
  462. | To -> ":to",("Specifies that the field of the abstract is a cast operation to the type identified in the function",[UsedOn TAbstractField])
  463. | ToString -> ":toString",("Internally used",[Internal])
  464. | Transient -> ":transient",("Adds the 'transient' flag to the class field",[Platform Java; UsedOn TClassField])
  465. | ValueUsed -> ":valueUsed",("Internally used by DCE to mark an abstract value as used",[Internal])
  466. | Volatile -> ":volatile",("",[Platforms [Java;Cs]])
  467. | Unbound -> ":unbound", ("Compiler internal to denote unbounded global variable",[])
  468. | UnifyMinDynamic -> ":unifyMinDynamic",("Allows a collection of types to unify to Dynamic",[UsedOn TClassField])
  469. | Unreflective -> ":unreflective",("",[Platform Cpp])
  470. | Unsafe -> ":unsafe",("Declares a class, or a method with the C#'s 'unsafe' flag",[Platform Cs; UsedOnEither [TClass;TClassField]])
  471. | Usage -> ":usage",("?",[])
  472. | Used -> ":used",("Internally used by DCE to mark a class or field as used",[Internal])
  473. | Value -> ":value",("Used to store default values for fields and function arguments",[UsedOn TClassField])
  474. | Void -> ":void",("Use Cpp native 'void' return type",[Platform Cpp])
  475. | Last -> assert false
  476. (* do not put any custom metadata after Last *)
  477. | Dollar s -> "$" ^ s,("",[])
  478. | Custom s -> s,("",[])
  479. let hmeta =
  480. let h = Hashtbl.create 0 in
  481. let rec loop i =
  482. let m = Obj.magic i in
  483. if m <> Last then begin
  484. Hashtbl.add h (fst (to_string m)) m;
  485. loop (i + 1);
  486. end;
  487. in
  488. loop 0;
  489. h
  490. let parse s = try Hashtbl.find hmeta (":" ^ s) with Not_found -> Custom (":" ^ s)
  491. let from_string s =
  492. if s = "" then Custom "" else match s.[0] with
  493. | ':' -> (try Hashtbl.find hmeta s with Not_found -> Custom s)
  494. | '$' -> Dollar (String.sub s 1 (String.length s - 1))
  495. | _ -> Custom s
  496. end
  497. let stats =
  498. {
  499. s_files_parsed = ref 0;
  500. s_classes_built = ref 0;
  501. s_methods_typed = ref 0;
  502. s_macros_called = ref 0;
  503. }
  504. let default_config =
  505. {
  506. pf_static = true;
  507. pf_sys = true;
  508. pf_locals_scope = true;
  509. pf_captured_scope = true;
  510. pf_unique_locals = false;
  511. pf_capture_policy = CPNone;
  512. pf_pad_nulls = false;
  513. pf_add_final_return = false;
  514. pf_overload = false;
  515. pf_pattern_matching = false;
  516. pf_can_skip_non_nullable_argument = true;
  517. pf_reserved_type_paths = [];
  518. }
  519. let get_config com =
  520. let defined f = PMap.mem (fst (Define.infos f)) com.defines in
  521. match com.platform with
  522. | Cross ->
  523. default_config
  524. | Flash8 ->
  525. {
  526. pf_static = false;
  527. pf_sys = false;
  528. pf_locals_scope = com.flash_version > 6.;
  529. pf_captured_scope = false;
  530. pf_unique_locals = false;
  531. pf_capture_policy = CPLoopVars;
  532. pf_pad_nulls = false;
  533. pf_add_final_return = false;
  534. pf_overload = false;
  535. pf_pattern_matching = false;
  536. pf_can_skip_non_nullable_argument = true;
  537. pf_reserved_type_paths = [];
  538. }
  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")];
  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")];
  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. {
  678. version = v;
  679. args = args;
  680. sys_args = args;
  681. debug = false;
  682. display = !display_default;
  683. verbose = false;
  684. foptimize = true;
  685. features = Hashtbl.create 0;
  686. platform = Cross;
  687. config = default_config;
  688. print = (fun s -> print_string s; flush stdout);
  689. run_command = Sys.command;
  690. std_path = [];
  691. class_path = [];
  692. main_class = None;
  693. defines = PMap.add "true" "1" (if !display_default <> DMNone then PMap.add "display" "1" PMap.empty else PMap.empty);
  694. package_rules = PMap.empty;
  695. file = "";
  696. types = [];
  697. filters = [];
  698. final_filters = [];
  699. modules = [];
  700. main = None;
  701. flash_version = 10.;
  702. resources = Hashtbl.create 0;
  703. php_front = None;
  704. php_lib = None;
  705. swf_libs = [];
  706. java_libs = [];
  707. net_libs = [];
  708. net_std = [];
  709. net_path_map = Hashtbl.create 0;
  710. c_args = [];
  711. neko_libs = [];
  712. php_prefix = None;
  713. js_gen = None;
  714. load_extern_type = [];
  715. defines_signature = None;
  716. get_macros = (fun() -> None);
  717. warning = (fun _ _ -> assert false);
  718. error = (fun _ _ -> assert false);
  719. basic = {
  720. tvoid = m;
  721. tint = m;
  722. tfloat = m;
  723. tbool = m;
  724. tnull = (fun _ -> assert false);
  725. tstring = m;
  726. tarray = (fun _ -> assert false);
  727. };
  728. file_lookup_cache = Hashtbl.create 0;
  729. stored_typed_exprs = PMap.empty;
  730. memory_marker = memory_marker;
  731. }
  732. let log com str =
  733. if com.verbose then com.print (str ^ "\n")
  734. let clone com =
  735. let t = com.basic in
  736. { com with
  737. basic = { t with tvoid = t.tvoid };
  738. main_class = None;
  739. features = Hashtbl.create 0;
  740. file_lookup_cache = Hashtbl.create 0;
  741. }
  742. let file_time file =
  743. try (Unix.stat file).Unix.st_mtime with _ -> 0.
  744. let get_signature com =
  745. match com.defines_signature with
  746. | Some s -> s
  747. | None ->
  748. let str = String.concat "@" (PMap.foldi (fun k v acc ->
  749. (* don't make much difference between these special compilation flags *)
  750. match k with
  751. | "display" | "use_rtti_doc" | "macrotimes" -> acc
  752. | _ -> k :: v :: acc
  753. ) com.defines []) in
  754. let s = Digest.string str in
  755. com.defines_signature <- Some s;
  756. s
  757. let file_extension file =
  758. match List.rev (ExtString.String.nsplit file ".") with
  759. | e :: _ -> String.lowercase e
  760. | [] -> ""
  761. let platforms = [
  762. Flash8;
  763. Js;
  764. Neko;
  765. Flash;
  766. Php;
  767. Cpp;
  768. Cs;
  769. Java;
  770. Python;
  771. ]
  772. let platform_name = function
  773. | Cross -> "cross"
  774. | Flash8 -> "flash8"
  775. | Js -> "js"
  776. | Neko -> "neko"
  777. | Flash -> "flash"
  778. | Php -> "php"
  779. | Cpp -> "cpp"
  780. | Cs -> "cs"
  781. | Java -> "java"
  782. | Python -> "python"
  783. let flash_versions = List.map (fun v ->
  784. let maj = int_of_float v in
  785. let min = int_of_float (mod_float (v *. 10.) 10.) in
  786. v, string_of_int maj ^ (if min = 0 then "" else "_" ^ string_of_int min)
  787. ) [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]
  788. let flash_version_tag = function
  789. | 6. -> 6
  790. | 7. -> 7
  791. | 8. -> 8
  792. | 9. -> 9
  793. | 10. | 10.1 -> 10
  794. | 10.2 -> 11
  795. | 10.3 -> 12
  796. | 11. -> 13
  797. | 11.1 -> 14
  798. | 11.2 -> 15
  799. | 11.3 -> 16
  800. | 11.4 -> 17
  801. | 11.5 -> 18
  802. | 11.6 -> 19
  803. | 11.7 -> 20
  804. | 11.8 -> 21
  805. | 11.9 -> 22
  806. | 12.0 -> 23
  807. | 13.0 -> 24
  808. | 14.0 -> 25
  809. | 15.0 -> 26
  810. | 16.0 -> 27
  811. | 17.0 -> 28
  812. | v -> failwith ("Invalid SWF version " ^ string_of_float v)
  813. let raw_defined ctx v =
  814. PMap.mem v ctx.defines
  815. let defined ctx v =
  816. raw_defined ctx (fst (Define.infos v))
  817. let raw_defined_value ctx k =
  818. PMap.find k ctx.defines
  819. let defined_value ctx v =
  820. raw_defined_value ctx (fst (Define.infos v))
  821. let defined_value_safe ctx v =
  822. try defined_value ctx v
  823. with Not_found -> ""
  824. let raw_define ctx v =
  825. let k,v = try ExtString.String.split v "=" with _ -> v,"1" in
  826. ctx.defines <- PMap.add k v ctx.defines;
  827. let k = String.concat "_" (ExtString.String.nsplit k "-") in
  828. ctx.defines <- PMap.add k v ctx.defines;
  829. ctx.defines_signature <- None
  830. let define_value ctx k v =
  831. raw_define ctx (fst (Define.infos k) ^ "=" ^ v)
  832. let define ctx v =
  833. raw_define ctx (fst (Define.infos v))
  834. let init_platform com pf =
  835. com.platform <- pf;
  836. let name = platform_name pf in
  837. let forbid acc p = if p = name || PMap.mem p acc then acc else PMap.add p Forbidden acc in
  838. com.package_rules <- List.fold_left forbid com.package_rules (List.map platform_name platforms);
  839. com.config <- get_config com;
  840. (* if com.config.pf_static then define com "static"; *)
  841. if com.config.pf_sys then define com Define.Sys else com.package_rules <- PMap.add "sys" Forbidden com.package_rules;
  842. raw_define com name
  843. let add_feature com f =
  844. Hashtbl.replace com.features f true
  845. let has_dce com =
  846. (try defined_value com Define.Dce <> "no" with Not_found -> false)
  847. (*
  848. TODO: The has_dce check is there because we mark types with @:directlyUsed in the DCE filter,
  849. which is not run in dce=no and thus we can't know if a type is used directly or not,
  850. so we just assume that they are.
  851. If we had dce filter always running (even with dce=no), we would have types marked with @:directlyUsed
  852. and we wouldn't need to generate unnecessary imports in dce=no, but that's good enough for now.
  853. *)
  854. let is_directly_used com meta =
  855. not (has_dce com) || Ast.Meta.has Ast.Meta.DirectlyUsed meta
  856. let rec has_feature com f =
  857. try
  858. Hashtbl.find com.features f
  859. with Not_found ->
  860. if com.types = [] then not (has_dce com) else
  861. match List.rev (ExtString.String.nsplit f ".") with
  862. | [] -> assert false
  863. | [cl] -> has_feature com (cl ^ ".*")
  864. | meth :: cl :: pack ->
  865. let r = (try
  866. let path = List.rev pack, cl in
  867. (match List.find (fun t -> t_path t = path && not (Ast.Meta.has Ast.Meta.RealPath (t_infos t).mt_meta)) com.types with
  868. | t when meth = "*" -> (match t with TAbstractDecl a -> Ast.Meta.has Ast.Meta.ValueUsed a.a_meta | _ ->
  869. Ast.Meta.has Ast.Meta.Used (t_infos t).mt_meta)
  870. | TClassDecl ({cl_extern = true} as c) when com.platform <> Js || cl <> "Array" && cl <> "Math" ->
  871. Meta.has Meta.Used (try PMap.find meth c.cl_statics with Not_found -> PMap.find meth c.cl_fields).cf_meta
  872. | TClassDecl c ->
  873. PMap.exists meth c.cl_statics || PMap.exists meth c.cl_fields
  874. | _ ->
  875. false)
  876. with Not_found ->
  877. false
  878. ) in
  879. let r = r || not (has_dce com) in
  880. Hashtbl.add com.features f r;
  881. r
  882. let allow_package ctx s =
  883. try
  884. if (PMap.find s ctx.package_rules) = Forbidden then ctx.package_rules <- PMap.remove s ctx.package_rules
  885. with Not_found ->
  886. ()
  887. let error msg p = raise (Abort (msg,p))
  888. let platform ctx p = ctx.platform = p
  889. let add_filter ctx f =
  890. ctx.filters <- f :: ctx.filters
  891. let add_final_filter ctx f =
  892. ctx.final_filters <- f :: ctx.final_filters
  893. let find_file ctx f =
  894. try
  895. (match Hashtbl.find ctx.file_lookup_cache f with
  896. | None -> raise Exit
  897. | Some f -> f)
  898. with Exit ->
  899. raise Not_found
  900. | Not_found ->
  901. let rec loop had_empty = function
  902. | [] when had_empty -> raise Not_found
  903. | [] -> loop true [""]
  904. | p :: l ->
  905. let file = p ^ f in
  906. if Sys.file_exists file then
  907. file
  908. else
  909. loop (had_empty || p = "") l
  910. in
  911. let r = (try Some (loop false ctx.class_path) with Not_found -> None) in
  912. Hashtbl.add ctx.file_lookup_cache f r;
  913. (match r with
  914. | None -> raise Not_found
  915. | Some f -> f)
  916. let get_full_path f = try Extc.get_full_path f with _ -> f
  917. 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
  918. let normalize_path p =
  919. let l = String.length p in
  920. if l = 0 then
  921. "./"
  922. else match p.[l-1] with
  923. | '\\' | '/' -> p
  924. | _ -> p ^ "/"
  925. let rec mkdir_recursive base dir_list =
  926. match dir_list with
  927. | [] -> ()
  928. | dir :: remaining ->
  929. let path = match base with
  930. | "" -> dir
  931. | "/" -> "/" ^ dir
  932. | _ -> base ^ "/" ^ dir
  933. in
  934. if not ( (path = "") || ( ((String.length path) = 2) && ((String.sub path 1 1) = ":") ) ) then
  935. if not (Sys.file_exists path) then
  936. Unix.mkdir path 0o755;
  937. mkdir_recursive (if (path = "") then "/" else path) remaining
  938. let mkdir_from_path path =
  939. let parts = Str.split_delim (Str.regexp "[\\/]+") path in
  940. match parts with
  941. | [] -> (* path was "" *) ()
  942. | _ ->
  943. let dir_list = List.rev (List.tl (List.rev parts)) in
  944. mkdir_recursive "" dir_list
  945. let mem_size v =
  946. Objsize.size_with_headers (Objsize.objsize v [] [])
  947. (* ------------------------- TIMERS ----------------------------- *)
  948. type timer_infos = {
  949. name : string;
  950. mutable start : float list;
  951. mutable total : float;
  952. }
  953. let get_time = Extc.time
  954. let htimers = Hashtbl.create 0
  955. let new_timer name =
  956. try
  957. let t = Hashtbl.find htimers name in
  958. t.start <- get_time() :: t.start;
  959. t
  960. with Not_found ->
  961. let t = { name = name; start = [get_time()]; total = 0.; } in
  962. Hashtbl.add htimers name t;
  963. t
  964. let curtime = ref []
  965. let close t =
  966. let start = (match t.start with
  967. | [] -> assert false
  968. | s :: l -> t.start <- l; s
  969. ) in
  970. let now = get_time() in
  971. let dt = now -. start in
  972. t.total <- t.total +. dt;
  973. let rec loop() =
  974. match !curtime with
  975. | [] -> failwith ("Timer " ^ t.name ^ " closed while not active")
  976. | tt :: l -> curtime := l; if t != tt then loop()
  977. in
  978. loop();
  979. (* because of rounding errors while adding small times, we need to make sure that we don't have start > now *)
  980. 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
  981. let timer name =
  982. let t = new_timer name in
  983. curtime := t :: !curtime;
  984. (function() -> close t)
  985. let rec close_times() =
  986. match !curtime with
  987. | [] -> ()
  988. | t :: _ -> close t; close_times()
  989. ;;
  990. Ast.Meta.to_string_ref := fun m -> fst (MetaInfo.to_string m)
  991. (* Taken from OCaml source typing/oprint.ml
  992. This is a better version of string_of_float which prints without loss of precision
  993. so that float_of_string (float_repres x) = x for all floats x
  994. *)
  995. let valid_float_lexeme s =
  996. let l = String.length s in
  997. let rec loop i =
  998. if i >= l then s ^ "." else
  999. match s.[i] with
  1000. | '0' .. '9' | '-' -> loop (i+1)
  1001. | _ -> s
  1002. in loop 0
  1003. let float_repres f =
  1004. match classify_float f with
  1005. | FP_nan -> "nan"
  1006. | FP_infinite ->
  1007. if f < 0.0 then "neg_infinity" else "infinity"
  1008. | _ ->
  1009. let float_val =
  1010. let s1 = Printf.sprintf "%.12g" f in
  1011. if f = float_of_string s1 then s1 else
  1012. let s2 = Printf.sprintf "%.15g" f in
  1013. if f = float_of_string s2 then s2 else
  1014. Printf.sprintf "%.18g" f
  1015. in valid_float_lexeme float_val