From 3cb7d88079181363699dd7e09b61fa571fc8253e Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Mon, 8 Jan 2024 08:20:30 +0100 Subject: [PATCH 01/13] [generators] add gctx.ml to lose dependency on common.ml --- src/compiler/generate.ml | 4 ++- src/context/common.ml | 19 ++++++++++ src/context/nativeLibraries.ml | 6 +++- src/generators/gctx.ml | 65 ++++++++++++++++++++++++++++++++++ src/generators/genjvm.ml | 65 +++++++++++++++++----------------- 5 files changed, 124 insertions(+), 35 deletions(-) create mode 100644 src/generators/gctx.ml diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index 1cbcd6df139..b3d724b439d 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -80,7 +80,9 @@ let generate ctx tctx ext actx = Gencs.generate,"cs" | Java -> if Common.defined com Jvm then - Genjvm.generate actx.jvm_flag,"java" + (fun com -> + Genjvm.generate actx.jvm_flag (Common.to_gctx com) + ),"java" else Genjava.generate,"java" | Python -> diff --git a/src/context/common.ml b/src/context/common.ml index b972218db0a..0be89298028 100644 --- a/src/context/common.ml +++ b/src/context/common.ml @@ -412,6 +412,25 @@ type context = { memory_marker : float array; } +let to_gctx com = { + Gctx.platform = com.platform; + defines = com.defines; + basic = com.basic; + debug = com.debug; + file = com.file; + features = com.features; + modules = com.modules; + main = com.main; + types = com.types; + resources = com.resources; + main_class = com.main_class; + native_libs = match com.platform with + | Java -> (com.native_libs.java_libs :> NativeLibraries.native_library_base list) + | Cs -> (com.native_libs.net_libs :> NativeLibraries.native_library_base list) + | Flash -> (com.native_libs.swf_libs :> NativeLibraries.native_library_base list) + | _ -> []; +} + let enter_stage com stage = (* print_endline (Printf.sprintf "Entering stage %s" (s_compiler_stage stage)); *) com.stage <- stage diff --git a/src/context/nativeLibraries.ml b/src/context/nativeLibraries.ml index 0ee95517450..c0769b827b6 100644 --- a/src/context/nativeLibraries.ml +++ b/src/context/nativeLibraries.ml @@ -23,7 +23,7 @@ type native_lib_flags = | FlagIsStd | FlagIsExtern -class virtual ['a,'data] native_library (name : string) (file_path : string) = object(self) +class virtual native_library_base (name : string) (file_path : string) = object(self) val mutable flags : native_lib_flags list = [] method add_flag flag = flags <- flag :: flags @@ -31,6 +31,10 @@ class virtual ['a,'data] native_library (name : string) (file_path : string) = o method get_name = name method get_file_path = file_path +end + +class virtual ['a,'data] native_library (name : string) (file_path : string) = object(self) + inherit native_library_base name file_path method virtual build : path -> pos -> Ast.package option method virtual close : unit diff --git a/src/generators/gctx.ml b/src/generators/gctx.ml new file mode 100644 index 00000000000..62cd56b59f2 --- /dev/null +++ b/src/generators/gctx.ml @@ -0,0 +1,65 @@ +open Globals +open Type + +type t = { + platform : platform; + defines : Define.define; + basic : basic_types; + debug : bool; + file : string; + features : (string,bool) Hashtbl.t; + modules : Type.module_def list; + main : Type.texpr option; + types : Type.module_type list; + resources : (string,string) Hashtbl.t; + main_class : path option; + native_libs : NativeLibraries.native_library_base list; +} + +let raw_defined gctx v = + Define.raw_defined gctx.defines v + +let has_dce gctx = + try + Define.defined_value gctx.defines Define.Dce <> "no" +with Not_found -> + false + +let rec has_feature gctx f = + try + Hashtbl.find gctx.features f + with Not_found -> + if gctx.types = [] then not (has_dce gctx) else + match List.rev (ExtString.String.nsplit f ".") with + | [] -> die "" __LOC__ + | [cl] -> has_feature gctx (cl ^ ".*") + | field :: cl :: pack -> + let r = (try + let path = List.rev pack, cl in + (match List.find (fun t -> t_path t = path && not (Meta.has Meta.RealPath (t_infos t).mt_meta)) gctx.types with + | t when field = "*" -> + not (has_dce gctx) || + (match t with TAbstractDecl a -> Meta.has Meta.ValueUsed a.a_meta | _ -> Meta.has Meta.Used (t_infos t).mt_meta) + | TClassDecl c when (has_class_flag c CExtern) && (gctx.platform <> Js || cl <> "Array" && cl <> "Math") -> + not (has_dce gctx) || Meta.has Meta.Used (try PMap.find field c.cl_statics with Not_found -> PMap.find field c.cl_fields).cf_meta + | TClassDecl c -> + PMap.exists field c.cl_statics || PMap.exists field c.cl_fields + | _ -> + false) + with Not_found -> + false + ) in + Hashtbl.add gctx.features f r; + r + +let get_entry_point gctx = + Option.map (fun path -> + let m = List.find (fun m -> m.m_path = path) gctx.modules in + let c = + match m.m_statics with + | Some c when (PMap.mem "main" c.cl_statics) -> c + | _ -> Option.get (ExtList.List.find_map (fun t -> match t with TClassDecl c when c.cl_path = path -> Some c | _ -> None) m.m_types) + in + let e = Option.get gctx.main in (* must be present at this point *) + (snd path, c, e) + ) gctx.main_class \ No newline at end of file diff --git a/src/generators/genjvm.ml b/src/generators/genjvm.ml index 657c594be02..14b46961062 100644 --- a/src/generators/genjvm.ml +++ b/src/generators/genjvm.ml @@ -19,7 +19,7 @@ open Globals open Ast -open Common +open Gctx open Type open Path open JvmGlobals @@ -58,7 +58,7 @@ end (* Haxe *) type generation_context = { - com : Common.context; + gctx : Gctx.t; out : jvm_output; t_runtime_exception : Type.t; entry_point : (tclass * texpr) option; @@ -505,7 +505,6 @@ class texpr_to_jvm (jm : JvmMethod.builder) (return_type : jsignature option) = object(self) - val com = gctx.com val code = jm#get_code val pool : JvmConstantPool.constant_pool = jc#get_pool @@ -521,7 +520,7 @@ class texpr_to_jvm method vtype t = jsignature_of_type gctx t - method mknull t = com.basic.tnull (follow t) + method mknull t = gctx.gctx.basic.tnull (follow t) (* locals *) @@ -988,13 +987,13 @@ class texpr_to_jvm store(); let ev = mk (TLocal v) v.v_type null_pos in let el = List.rev_map (fun case -> - let f e' = mk (TBinop(OpEq,ev,e')) com.basic.tbool e'.epos in + let f e' = mk (TBinop(OpEq,ev,e')) gctx.gctx.basic.tbool e'.epos in let e_cond = match case.case_patterns with | [] -> die "" __LOC__ | [e] -> f e | e :: el -> List.fold_left (fun eacc e -> - mk (TBinop(OpBoolOr,eacc,f e)) com.basic.tbool e.epos + mk (TBinop(OpBoolOr,eacc,f e)) gctx.gctx.basic.tbool e.epos ) (f e) el in (e_cond,case.case_expr) @@ -2109,7 +2108,7 @@ class texpr_to_jvm | TParenthesis e1 | TMeta(_,e1) -> self#texpr ret e1 | TFor(v,e1,e2) -> - self#texpr ret (Texpr.for_remap com.basic v e1 e2 e.epos) + self#texpr ret (Texpr.for_remap gctx.gctx.basic v e1 e2 e.epos) | TEnumIndex e1 -> self#texpr rvalue_any e1; jm#invokevirtual java_enum_path "ordinal" (method_sig [] (Some TInt)) @@ -2560,9 +2559,9 @@ class tclass_to_jvm gctx c = object(self) | None -> if c.cl_path = (["haxe"],"Resource") && cf.cf_name = "content" then begin let el = Hashtbl.fold (fun name _ acc -> - Texpr.Builder.make_string gctx.com.basic name null_pos :: acc - ) gctx.com.resources [] in - let e = mk (TArrayDecl el) (gctx.com.basic.tarray gctx.com.basic.tstring) null_pos in + Texpr.Builder.make_string gctx.gctx.basic name null_pos :: acc + ) gctx.gctx.resources [] in + let e = mk (TArrayDecl el) (gctx.gctx.basic.tarray gctx.gctx.basic.tstring) null_pos in default e; end; | Some e when mtype <> MStatic -> @@ -2603,7 +2602,7 @@ class tclass_to_jvm gctx c = object(self) let jsig = method_sig [array_sig string_sig] None in let jm = jc#spawn_method "main" jsig [MPublic;MStatic] in let _,load,_ = jm#add_local "args" (TArray(string_sig,None)) VarArgument in - if has_feature gctx.com "haxe.root.Sys.args" then begin + if has_feature gctx.gctx "haxe.root.Sys.args" then begin load(); jm#putstatic (["haxe";"root"],"Sys") "_args" (TArray(string_sig,None)) end; @@ -2838,7 +2837,7 @@ let generate_enum gctx en = jm_values#new_native_array (object_path_sig jc_enum#get_this_path) fl; jm_values#return; (* Add __meta__ TODO: do this via annotations instead? *) - begin match Texpr.build_metadata gctx.com.basic (TEnumDecl en) with + begin match Texpr.build_metadata gctx.gctx.basic (TEnumDecl en) with | None -> () | Some e -> @@ -3000,7 +2999,7 @@ module Preprocessor = struct | _ -> () ) m.m_types - ) gctx.com.modules; + ) gctx.gctx.modules; (* preprocess classes *) List.iter (fun mt -> match mt with @@ -3008,24 +3007,24 @@ module Preprocessor = struct if not (has_class_flag c CInterface) then gctx.preprocessor#preprocess_class c else check_single_method_interface gctx c; | _ -> () - ) gctx.com.types; + ) gctx.gctx.types; (* find typedef-interface implementations *) List.iter (fun mt -> match mt with | TClassDecl c when not (has_class_flag c CInterface) && not (has_class_flag c CExtern) -> gctx.typedef_interfaces#process_class c; | _ -> () - ) gctx.com.types + ) gctx.gctx.types end -let generate jvm_flag com = - let path = FilePath.parse com.file in - let jar_name,entry_point = match get_entry_point com with +let generate jvm_flag gctx = + let path = FilePath.parse gctx.file in + let jar_name,entry_point = match get_entry_point gctx with | Some (jarname,cl,expr) -> jarname, Some (cl,expr) | None -> "jar",None in let compression_level = try - int_of_string (Define.defined_value com.defines Define.JvmCompressionLevel) + int_of_string (Define.defined_value gctx.defines Define.JvmCompressionLevel) with _ -> 6 in @@ -3038,10 +3037,10 @@ let generate jvm_flag com = | Some _ -> begin match path.directory with | None -> - "./",create_jar ("./" ^ com.file) + "./",create_jar ("./" ^ gctx.file) | Some dir -> mkdir_from_path dir; - add_trailing_slash dir,create_jar com.file + add_trailing_slash dir,create_jar gctx.file end | None -> match path.directory with | Some dir -> @@ -3050,25 +3049,25 @@ let generate jvm_flag com = | None -> failwith "Please specify an output file name" end else begin - let jar_name = if com.debug then jar_name ^ "-Debug" else jar_name in - let jar_dir = add_trailing_slash com.file in + let jar_name = if gctx.debug then jar_name ^ "-Debug" else jar_name in + let jar_dir = add_trailing_slash gctx.file in let jar_path = Printf.sprintf "%s%s.jar" jar_dir jar_name in jar_dir,create_jar jar_path end in let anon_identification = new tanon_identification haxe_dynamic_object_path in let dynamic_level = try - int_of_string (Define.defined_value com.defines Define.JvmDynamicLevel) + int_of_string (Define.defined_value gctx.defines Define.JvmDynamicLevel) with _ -> 1 in if dynamic_level < 0 || dynamic_level > 2 then failwith "Invalid value for -D jvm.dynamic-level: Must be >=0 and <= 2"; let gctx = { - com = com; + gctx = gctx; out = out; - t_runtime_exception = TInst(resolve_class com (["java";"lang"],"RuntimeException"),[]); + t_runtime_exception = TInst(resolve_class gctx (["java";"lang"],"RuntimeException"),[]); entry_point = entry_point; - t_exception = TInst(resolve_class com (["java";"lang"],"Exception"),[]); - t_throwable = TInst(resolve_class com (["java";"lang"],"Throwable"),[]); + t_exception = TInst(resolve_class gctx (["java";"lang"],"Exception"),[]); + t_throwable = TInst(resolve_class gctx (["java";"lang"],"Throwable"),[]); anon_identification = anon_identification; preprocessor = Obj.magic (); typedef_interfaces = Obj.magic (); @@ -3078,12 +3077,12 @@ let generate jvm_flag com = default_export_config = { export_debug = true; }; - detail_times = Common.raw_defined com "jvm_times"; + detail_times = Gctx.raw_defined gctx "jvm_times"; timer = new Timer.timer ["generate";"java"]; jar_compression_level = compression_level; dynamic_level = dynamic_level; } in - gctx.preprocessor <- new preprocessor com.basic (jsignature_of_type gctx); + gctx.preprocessor <- new preprocessor gctx.gctx.basic (jsignature_of_type gctx); gctx.typedef_interfaces <- new typedef_interfaces gctx.preprocessor#get_infos anon_identification; gctx.typedef_interfaces#add_interface_rewrite (["haxe";"root"],"Iterator") (["java";"util"],"Iterator") true; let class_paths = ExtList.List.filter_map (fun java_lib -> @@ -3100,13 +3099,13 @@ let generate jvm_flag com = close_out ch_out; Some (Printf.sprintf "lib/%s \n" name) end - ) com.native_libs.java_libs in + ) gctx.gctx.native_libs in Hashtbl.iter (fun name v -> let filename = StringHelper.escape_res_name name ['/';'-'] in gctx.out#add_entry v filename; - ) com.resources; + ) gctx.gctx.resources; let generate_real_types () = - List.iter (generate_module_type gctx) com.types; + List.iter (generate_module_type gctx) gctx.gctx.types; in let generate_typed_interfaces () = Hashtbl.iter (fun _ c -> generate_module_type gctx (TClassDecl c)) gctx.typedef_interfaces#get_interfaces; From 87dff417054ef8a1f6830064957d3d5d596ff1b4 Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Mon, 8 Jan 2024 09:04:49 +0100 Subject: [PATCH 02/13] also port genhl to gctx --- src/compiler/generate.ml | 4 +- src/context/common.ml | 88 ++--------------------------------- src/core/stringHelper.ml | 90 +++++++++++++++++++++++++++++++++++- src/generators/gctx.ml | 25 +++++++++- src/generators/genhl.ml | 30 ++++++------ src/generators/genjs.ml | 2 +- src/generators/hl2c.ml | 8 ++-- src/generators/hlinterp.ml | 16 +++---- src/macro/eval/evalStdLib.ml | 2 +- 9 files changed, 149 insertions(+), 116 deletions(-) diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index b3d724b439d..d6e17af1e65 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -88,7 +88,9 @@ let generate ctx tctx ext actx = | Python -> Genpy.generate,"python" | Hl -> - Genhl.generate,"hl" + (fun com -> + Genhl.generate (Common.to_gctx com) + ),"hl" | Eval -> (fun _ -> MacroContext.interpret tctx),"eval" | Cross diff --git a/src/context/common.ml b/src/context/common.ml index 0be89298028..7fb667144b8 100644 --- a/src/context/common.ml +++ b/src/context/common.ml @@ -416,8 +416,12 @@ let to_gctx com = { Gctx.platform = com.platform; defines = com.defines; basic = com.basic; + class_path = com.class_path; + run_command = com.run_command; + run_command_args = com.run_command_args; debug = com.debug; file = com.file; + version = com.version; features = com.features; modules = com.modules; main = com.main; @@ -1191,90 +1195,6 @@ let hash f = done; if Sys.word_size = 64 then Int32.to_int (Int32.shift_right (Int32.shift_left (Int32.of_int !h) 1) 1) else !h -let url_encode s add_char = - let hex = "0123456789ABCDEF" in - for i = 0 to String.length s - 1 do - let c = String.unsafe_get s i in - match c with - | 'A'..'Z' | 'a'..'z' | '0'..'9' | '_' | '-' | '.' -> - add_char c - | _ -> - add_char '%'; - add_char (String.unsafe_get hex (int_of_char c lsr 4)); - add_char (String.unsafe_get hex (int_of_char c land 0xF)); - done - -let url_encode_s s = - let b = Buffer.create 0 in - url_encode s (Buffer.add_char b); - Buffer.contents b - -(* UTF8 *) - -let to_utf8 str p = - let u8 = try - UTF8.validate str; - str; - with - UTF8.Malformed_code -> - (* ISO to utf8 *) - let b = UTF8.Buf.create 0 in - String.iter (fun c -> UTF8.Buf.add_char b (UCharExt.of_char c)) str; - UTF8.Buf.contents b - in - let ccount = ref 0 in - UTF8.iter (fun c -> - let c = UCharExt.code c in - if (c >= 0xD800 && c <= 0xDFFF) || c >= 0x110000 then Error.abort "Invalid unicode char" p; - incr ccount; - if c > 0x10000 then incr ccount; - ) u8; - u8, !ccount - -let utf16_add buf c = - let add c = - Buffer.add_char buf (char_of_int (c land 0xFF)); - Buffer.add_char buf (char_of_int (c lsr 8)); - in - if c >= 0 && c < 0x10000 then begin - if c >= 0xD800 && c <= 0xDFFF then failwith ("Invalid unicode char " ^ string_of_int c); - add c; - end else if c < 0x110000 then begin - let c = c - 0x10000 in - add ((c asr 10) + 0xD800); - add ((c land 1023) + 0xDC00); - end else - failwith ("Invalid unicode char " ^ string_of_int c) - -let utf8_to_utf16 str zt = - let b = Buffer.create (String.length str * 2) in - (try UTF8.iter (fun c -> utf16_add b (UCharExt.code c)) str with Invalid_argument _ | UCharExt.Out_of_range -> ()); (* if malformed *) - if zt then utf16_add b 0; - Buffer.contents b - -let utf16_to_utf8 str = - let b = Buffer.create 0 in - let add c = Buffer.add_char b (char_of_int (c land 0xFF)) in - let get i = int_of_char (String.unsafe_get str i) in - let rec loop i = - if i >= String.length str then () - else begin - let c = get i in - if c < 0x80 then begin - add c; - loop (i + 2); - end else if c < 0x800 then begin - let c = c lor ((get (i + 1)) lsl 8) in - add c; - add (c lsr 8); - loop (i + 2); - end else - die "" __LOC__; - end - in - loop 0; - Buffer.contents b - let add_diagnostics_message ?(depth = 0) ?(code = None) com s p kind sev = if sev = MessageSeverity.Error then com.has_error <- true; let di = com.shared.shared_display_information in diff --git a/src/core/stringHelper.ml b/src/core/stringHelper.ml index ab6c57df5cd..8593ee57718 100644 --- a/src/core/stringHelper.ml +++ b/src/core/stringHelper.ml @@ -1,3 +1,6 @@ +open Globals +open Extlib_leftovers + let uppercase s = let bytes = Bytes.of_string s in Bytes.iteri @@ -57,4 +60,89 @@ let escape_res_name name allowed = else if List.mem chr allowed then Char.escaped chr else - "-x" ^ (string_of_int (Char.code chr))) name \ No newline at end of file + "-x" ^ (string_of_int (Char.code chr))) name + + +(* UTF8 *) + +let to_utf8 str p = + let u8 = try + UTF8.validate str; + str; + with + UTF8.Malformed_code -> + (* ISO to utf8 *) + let b = UTF8.Buf.create 0 in + String.iter (fun c -> UTF8.Buf.add_char b (UCharExt.of_char c)) str; + UTF8.Buf.contents b + in + let ccount = ref 0 in + UTF8.iter (fun c -> + let c = UCharExt.code c in + if (c >= 0xD800 && c <= 0xDFFF) || c >= 0x110000 then failwith "Invalid unicode char"; + incr ccount; + if c > 0x10000 then incr ccount; + ) u8; + u8, !ccount + +let utf16_add buf c = + let add c = + Buffer.add_char buf (char_of_int (c land 0xFF)); + Buffer.add_char buf (char_of_int (c lsr 8)); + in + if c >= 0 && c < 0x10000 then begin + if c >= 0xD800 && c <= 0xDFFF then failwith ("Invalid unicode char " ^ string_of_int c); + add c; + end else if c < 0x110000 then begin + let c = c - 0x10000 in + add ((c asr 10) + 0xD800); + add ((c land 1023) + 0xDC00); + end else + failwith ("Invalid unicode char " ^ string_of_int c) + +let utf8_to_utf16 str zt = + let b = Buffer.create (String.length str * 2) in + (try UTF8.iter (fun c -> utf16_add b (UCharExt.code c)) str with Invalid_argument _ | UCharExt.Out_of_range -> ()); (* if malformed *) + if zt then utf16_add b 0; + Buffer.contents b + +let utf16_to_utf8 str = + let b = Buffer.create 0 in + let add c = Buffer.add_char b (char_of_int (c land 0xFF)) in + let get i = int_of_char (String.unsafe_get str i) in + let rec loop i = + if i >= String.length str then () + else begin + let c = get i in + if c < 0x80 then begin + add c; + loop (i + 2); + end else if c < 0x800 then begin + let c = c lor ((get (i + 1)) lsl 8) in + add c; + add (c lsr 8); + loop (i + 2); + end else + die "" __LOC__; + end + in + loop 0; + Buffer.contents b + +let url_encode s add_char = + let hex = "0123456789ABCDEF" in + for i = 0 to String.length s - 1 do + let c = String.unsafe_get s i in + match c with + | 'A'..'Z' | 'a'..'z' | '0'..'9' | '_' | '-' | '.' -> + add_char c + | _ -> + add_char '%'; + add_char (String.unsafe_get hex (int_of_char c lsr 4)); + add_char (String.unsafe_get hex (int_of_char c land 0xF)); + done + +let url_encode_s s = + let b = Buffer.create 0 in + url_encode s (Buffer.add_char b); + Buffer.contents b \ No newline at end of file diff --git a/src/generators/gctx.ml b/src/generators/gctx.ml index 62cd56b59f2..02aaaf0285f 100644 --- a/src/generators/gctx.ml +++ b/src/generators/gctx.ml @@ -4,9 +4,13 @@ open Type type t = { platform : platform; defines : Define.define; + class_path : string list; + run_command : string -> int; + run_command_args : string -> string list -> int; basic : basic_types; debug : bool; file : string; + version : int; features : (string,bool) Hashtbl.t; modules : Type.module_def list; main : Type.texpr option; @@ -16,6 +20,20 @@ type t = { native_libs : NativeLibraries.native_library_base list; } +let defined com s = + Define.defined com.defines s + +let defined_value com v = + Define.defined_value com.defines v + +let define_value com k v = + Define.define_value com.defines k v + +let defined_value_safe ?default com v = + match default with + | Some s -> Define.defined_value_safe ~default:s com.defines v + | None -> Define.defined_value_safe com.defines v + let raw_defined gctx v = Define.raw_defined gctx.defines v @@ -62,4 +80,9 @@ let get_entry_point gctx = in let e = Option.get gctx.main in (* must be present at this point *) (snd path, c, e) - ) gctx.main_class \ No newline at end of file + ) gctx.main_class + +let map_source_header com f = + match defined_value_safe com Define.SourceHeader with + | "" -> () + | s -> f s \ No newline at end of file diff --git a/src/generators/genhl.ml b/src/generators/genhl.ml index b00adbdf181..edd7048f5f3 100644 --- a/src/generators/genhl.ml +++ b/src/generators/genhl.ml @@ -24,7 +24,7 @@ open Globals open Ast open Type open Error -open Common +open Gctx open Hlcode (* compiler *) @@ -84,7 +84,7 @@ type constval = | CString of string type context = { - com : Common.context; + com : Gctx.t; cglobals : (string, ttype) lookup; cstrings : (string, string) lookup; cbytes : (bytes, bytes) lookup; @@ -322,7 +322,7 @@ let set_curpos ctx p = let make_debug ctx arr = let get_relative_path p = - match Common.defined ctx.com Common.Define.AbsolutePath with + match Gctx.defined ctx.com Define.AbsolutePath with | true -> if (Filename.is_relative p.pfile) then Filename.concat (Sys.getcwd()) p.pfile else p.pfile @@ -332,7 +332,7 @@ let make_debug ctx arr = let base = List.find (fun path -> let l = String.length path in len > l && String.sub p.pfile 0 l = path - ) ctx.com.Common.class_path in + ) ctx.com.Gctx.class_path in let l = String.length base in String.sub p.pfile l (len - l) with Not_found -> @@ -3389,7 +3389,7 @@ let generate_static ctx c f = | (Meta.HlNative,[(EConst(String(lib,_)),_)] ,_ ) :: _ -> add_native lib f.cf_name | (Meta.HlNative,[(EConst(Float(ver,_)),_)] ,_ ) :: _ -> - let cur_ver = (try Common.defined_value ctx.com Define.HlVer with Not_found -> "") in + let cur_ver = (try Gctx.defined_value ctx.com Define.HlVer with Not_found -> "") in if cur_ver < ver then let gen_content() = op ctx (OThrow (make_string ctx ("Requires compiling with -D hl-ver=" ^ ver ^ ".0 or higher") null_pos)); @@ -4054,7 +4054,7 @@ let create_context com is_macro dump = let ctx = { com = com; is_macro = is_macro; - optimize = not (Common.raw_defined com "hl_no_opt"); + optimize = not (Gctx.raw_defined com "hl_no_opt"); dump_out = if dump then Some (IO.output_channel (open_out_bin "dump/hlopt.txt")) else None; m = method_context 0 HVoid null_capture false; cints = new_lookup(); @@ -4173,8 +4173,8 @@ let make_context_sign com = let prev_sign = ref "" and prev_data = ref "" let generate com = - let dump = Common.defined com Define.Dump in - let hl_check = Common.raw_defined com "hl_check" in + let dump = Gctx.defined com Define.Dump in + let hl_check = Gctx.raw_defined com "hl_check" in let sign = make_context_sign com in if sign = !prev_sign && not dump && not hl_check then begin @@ -4194,7 +4194,7 @@ let generate com = Hlcode.dump (fun s -> output_string ch (s ^ "\n")) code; close_out ch; end; - (*if Common.raw_defined com "hl_dump_spec" then begin + (*if Gctx.raw_defined com "hl_dump_spec" then begin let ch = open_out_bin "dump/hlspec.txt" in let write s = output_string ch (s ^ "\n") in Array.iter (fun f -> @@ -4220,19 +4220,19 @@ let generate com = if Path.file_extension com.file = "c" then begin let gnames = Array.make (Array.length code.globals) "" in PMap.iter (fun n i -> gnames.(i) <- n) ctx.cglobals.map; - if not (Common.defined com Define.SourceHeader) then begin + if not (Gctx.defined com Define.SourceHeader) then begin let version_major = com.version / 1000 in let version_minor = (com.version mod 1000) / 100 in let version_revision = (com.version mod 100) in - Common.define_value com Define.SourceHeader (Printf.sprintf "Generated by HLC %d.%d.%d (HL v%d)" version_major version_minor version_revision code.version); + Gctx.define_value com Define.SourceHeader (Printf.sprintf "Generated by HLC %d.%d.%d (HL v%d)" version_major version_minor version_revision code.version); end; Hl2c.write_c com com.file code gnames; let t = Timer.timer ["nativecompile";"hl"] in - if not (Common.defined com Define.NoCompilation) && com.run_command_args "haxelib" ["run";"hashlink";"build";escape_command com.file] <> 0 then failwith "Build failed"; + if not (Gctx.defined com Define.NoCompilation) && com.run_command_args "haxelib" ["run";"hashlink";"build";escape_command com.file] <> 0 then failwith "Build failed"; t(); end else begin let ch = IO.output_string() in - write_code ch code (not (Common.raw_defined com "hl_no_debug")); + write_code ch code (not (Gctx.raw_defined com "hl_no_debug")); let str = IO.close_out ch in let ch = open_out_bin com.file in output_string ch str; @@ -4242,10 +4242,10 @@ let generate com = end; Hlopt.clean_cache(); t(); - if Common.raw_defined com "run" then begin + if Gctx.raw_defined com "run" then begin if com.run_command_args "haxelib" ["run";"hashlink";"run";escape_command com.file] <> 0 then failwith "Failed to run HL"; end; - if Common.defined com Define.Interp then + if Gctx.defined com Define.Interp then try let t = Timer.timer ["generate";"hl";"interp"] in let ctx = Hlinterp.create true in diff --git a/src/generators/genjs.ml b/src/generators/genjs.ml index 53fe22012f3..fa2adb04ebc 100644 --- a/src/generators/genjs.ml +++ b/src/generators/genjs.ml @@ -2006,7 +2006,7 @@ let generate com = | Some smap -> write_mappings ctx.com smap "file:///"; let basefile = Filename.basename com.file in - print ctx "\n//# sourceMappingURL=%s.map" (url_encode_s basefile); + print ctx "\n//# sourceMappingURL=%s.map" (StringHelper.url_encode_s basefile); | None -> try Sys.remove (com.file ^ ".map") with _ -> ()); flush ctx; Option.may (fun chan -> close_out chan) ctx.chan diff --git a/src/generators/hl2c.ml b/src/generators/hl2c.ml index 035b9838be5..b222c1248d9 100644 --- a/src/generators/hl2c.ml +++ b/src/generators/hl2c.ml @@ -78,7 +78,7 @@ type context = { mutable file_prefix : string; mutable fun_index : int; mutable type_module : (ttype, code_module) PMap.t; - gcon : Common.context; + gcon : Gctx.t; } let sprintf = Printf.sprintf @@ -345,7 +345,7 @@ let short_digest str = let open_file ctx file = if ctx.curfile <> "" then close_file ctx; if file <> "hlc.json" then - Codegen.map_source_header ctx.gcon (fun s -> define ctx (sprintf "// %s" s)); + Gctx.map_source_header ctx.gcon (fun s -> define ctx (sprintf "// %s" s)); ctx.curfile <- file; ctx.fun_index <- 0; ctx.file_prefix <- (short_digest file) ^ "_" @@ -1457,7 +1457,7 @@ let write_c com file (code:code) gnames = let bnames = Array.map (fun b -> "bytes$" ^ short_digest (Digest.to_hex (Digest.bytes b))) code.bytes in let ctx = { - version = com.Common.version; + version = com.Gctx.version; out = Buffer.create 1024; tabs = ""; hlcode = code; @@ -1572,7 +1572,7 @@ let write_c com file (code:code) gnames = in Array.iteri (fun i str -> if String.length str >= string_data_limit then begin - let s = Common.utf8_to_utf16 str true in + let s = StringHelper.utf8_to_utf16 str true in sline "// %s..." (String.escaped (String.sub str 0 (string_data_limit-4))); output ctx (Printf.sprintf "vbyte string$%s[] = {" (short_digest str)); output_bytes (output ctx) s; diff --git a/src/generators/hlinterp.ml b/src/generators/hlinterp.ml index 8c32aced375..ec20f8b048e 100644 --- a/src/generators/hlinterp.ml +++ b/src/generators/hlinterp.ml @@ -293,7 +293,7 @@ let fstr = function | FFun f -> "function@" ^ string_of_int f.findex | FNativeFun (s,_,_) -> "native[" ^ s ^ "]" -let caml_to_hl str = Common.utf8_to_utf16 str true +let caml_to_hl str = StringHelper.utf8_to_utf16 str true let hash ctx str = let h = hl_hash str in @@ -318,7 +318,7 @@ let utf16_iter f s = loop 0 let utf16_char buf c = - Common.utf16_add buf (int_of_char c) + StringHelper.utf16_add buf (int_of_char c) let hl_to_caml str = let utf16_eof s = @@ -1777,9 +1777,9 @@ let load_native ctx lib name t = if c >= int_of_char 'a' && c <= int_of_char 'z' then c + int_of_char 'A' - int_of_char 'a' else c in - Common.utf16_add buf c + StringHelper.utf16_add buf c ) (String.sub s (int pos) ((int len) lsl 1)); - Common.utf16_add buf 0; + StringHelper.utf16_add buf 0; VBytes (Buffer.contents buf) | _ -> Globals.die "" __LOC__) | "ucs2_lower" -> @@ -1791,9 +1791,9 @@ let load_native ctx lib name t = if c >= int_of_char 'A' && c <= int_of_char 'Z' then c + int_of_char 'a' - int_of_char 'A' else c in - Common.utf16_add buf c + StringHelper.utf16_add buf c ) (String.sub s (int pos) ((int len) lsl 1)); - Common.utf16_add buf 0; + StringHelper.utf16_add buf 0; VBytes (Buffer.contents buf) | _ -> Globals.die "" __LOC__) | "url_encode" -> @@ -1801,8 +1801,8 @@ let load_native ctx lib name t = | [VBytes s; VRef (r, HI32)] -> let s = hl_to_caml s in let buf = Buffer.create 0 in - Common.url_encode s (utf16_char buf); - Common.utf16_add buf 0; + StringHelper.url_encode s (utf16_char buf); + StringHelper.utf16_add buf 0; let str = Buffer.contents buf in set_ref r (to_int (String.length str lsr 1 - 1)); VBytes str diff --git a/src/macro/eval/evalStdLib.ml b/src/macro/eval/evalStdLib.ml index 7cdb911bb58..a69d09e7ecb 100644 --- a/src/macro/eval/evalStdLib.ml +++ b/src/macro/eval/evalStdLib.ml @@ -2440,7 +2440,7 @@ end module StdStringTools = struct let url_encode s = let b = Buffer.create 0 in - Common.url_encode s (Buffer.add_char b); + StringHelper.url_encode s (Buffer.add_char b); Buffer.contents b let fastCodeAt = StdString.charCodeAt From 49ae7db1d51d57ecc72e4eaaab487dedd37c3151 Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 09:14:28 +0100 Subject: [PATCH 03/13] adapt genjs argh --- src/codegen/codegen.ml | 10 +--- src/compiler/generate.ml | 4 +- src/context/common.ml | 10 ++-- src/filters/ES6Ctors.ml | 2 +- src/generators/cpp/cppSourceWriter.ml | 2 +- src/generators/cpp/gen/cppGen.ml | 2 +- src/generators/gctx.ml | 12 +++-- src/generators/gctx_todo.ml | 9 ++++ src/generators/genjs.ml | 70 +++++++++------------------ src/generators/genlua.ml | 6 +-- src/generators/genphp7.ml | 6 +-- src/generators/genpy.ml | 4 +- src/generators/hl2c.ml | 2 +- src/generators/jsSourcemap.ml | 4 +- src/macro/macroApi.ml | 6 +-- src/typing/macroContext.ml | 2 +- 16 files changed, 67 insertions(+), 84 deletions(-) create mode 100644 src/generators/gctx_todo.ml diff --git a/src/codegen/codegen.ml b/src/codegen/codegen.ml index 00ee5968e28..5dbd0b4f289 100644 --- a/src/codegen/codegen.ml +++ b/src/codegen/codegen.ml @@ -453,12 +453,12 @@ module UnificationCallback = struct List.map (fun e -> f e t_dynamic) el end;; -let interpolate_code com code tl f_string f_expr p = +let interpolate_code error code tl f_string f_expr p = let exprs = Array.of_list tl in let i = ref 0 in let err msg = let pos = { p with pmin = p.pmin + !i } in - com.error msg pos + error msg pos in let regex = Str.regexp "[{}]" in let rec loop m = match m with @@ -487,12 +487,6 @@ let interpolate_code com code tl f_string f_expr p = in loop (Str.full_split regex code) -let map_source_header com f = - match Common.defined_value_safe com Define.SourceHeader with - | "" -> () - | s -> f s - - (* Static extensions for classes *) module ExtClass = struct let add_static_init c cf e p = diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index b4c427df88a..ec827842d10 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -178,7 +178,9 @@ let generate ctx tctx ext actx = | Neko -> Genneko.generate,"neko" | Js -> - Genjs.generate,"js" + (fun com -> + Genjs.generate com.js_gen (Common.to_gctx com) + ),"js" | Lua -> Genlua.generate,"lua" | Php -> diff --git a/src/context/common.ml b/src/context/common.ml index 34452987ebc..f6008fd5ba8 100644 --- a/src/context/common.ml +++ b/src/context/common.ml @@ -445,10 +445,11 @@ let to_gctx com = { main = com.main; types = com.types; resources = com.resources; - native_libs = match com.platform with + native_libs = (match com.platform with | Jvm -> (com.native_libs.java_libs :> NativeLibraries.native_library_base list) | Flash -> (com.native_libs.swf_libs :> NativeLibraries.native_library_base list) - | _ -> []; + | _ -> []); + include_files = com.include_files; } let enter_stage com stage = @@ -540,9 +541,6 @@ let defines_for_external ctx = | split -> PMap.add (String.concat "-" split) v added_underscore; ) ctx.defines.values PMap.empty -let get_es_version com = - try int_of_string (defined_value com Define.JsEs) with _ -> 0 - let short_platform_name = function | Cross -> "x" | Js -> "js" @@ -605,7 +603,7 @@ let get_config com = (* impossible to reach. see update_platform_config *) raise Exit | Js -> - let es6 = get_es_version com >= 6 in + let es6 = Gctx_todo.get_es_version com.defines >= 6 in { default_config with pf_static = false; diff --git a/src/filters/ES6Ctors.ml b/src/filters/ES6Ctors.ml index 8dd2b526fcb..82126bb68d0 100644 --- a/src/filters/ES6Ctors.ml +++ b/src/filters/ES6Ctors.ml @@ -16,7 +16,7 @@ along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *) -open Common +open Gctx open Globals open Type open Texpr.Builder diff --git a/src/generators/cpp/cppSourceWriter.ml b/src/generators/cpp/cppSourceWriter.ml index 477e956c5c9..33109d69cb0 100644 --- a/src/generators/cpp/cppSourceWriter.ml +++ b/src/generators/cpp/cppSourceWriter.ml @@ -166,7 +166,7 @@ let new_source_file common_ctx base_dir sub_dir extension class_path = let file = cached_source_writer common_ctx (full_dir ^ "/" ^ snd class_path ^ extension) in - Codegen.map_source_header common_ctx (fun s -> + Gctx_todo.map_source_header common_ctx.defines (fun s -> file#write_h (Printf.sprintf "// %s\n" s)); file diff --git a/src/generators/cpp/gen/cppGen.ml b/src/generators/cpp/gen/cppGen.ml index 2a07db66dde..dfe0faecca0 100644 --- a/src/generators/cpp/gen/cppGen.ml +++ b/src/generators/cpp/gen/cppGen.ml @@ -1408,7 +1408,7 @@ let gen_cpp_ast_expression_tree ctx class_name func_name function_args out spacer; writer#end_block) | CppCode (value, exprs) -> - Codegen.interpolate_code ctx.ctx_common (format_code value) exprs out + Codegen.interpolate_code ctx.ctx_common.error (format_code value) exprs out (fun e -> gen e) expr.cpppos | CppTCast (expr, cppType) -> ( diff --git a/src/generators/gctx.ml b/src/generators/gctx.ml index 807c4095f7b..69d1ffaccf3 100644 --- a/src/generators/gctx.ml +++ b/src/generators/gctx.ml @@ -28,6 +28,7 @@ type t = { types : Type.module_type list; resources : (string,string) Hashtbl.t; native_libs : NativeLibraries.native_library_base list; + include_files : (string * string) list; } let defined com s = @@ -47,12 +48,18 @@ let defined_value_safe ?default com v = let raw_defined gctx v = Define.raw_defined gctx.defines v +let add_feature gctx f = + Hashtbl.replace gctx.features f true + let has_dce gctx = try Define.defined_value gctx.defines Define.Dce <> "no" with Not_found -> false +let is_directly_used gctx meta = + not (has_dce gctx) || Meta.has Meta.DirectlyUsed meta + let rec has_feature gctx f = try Hashtbl.find gctx.features f @@ -91,8 +98,3 @@ let get_entry_point gctx = let e = Option.get gctx.main.main_expr in (* must be present at this point *) (snd path, c, e) ) gctx.main.main_class - -let map_source_header com f = - match defined_value_safe com Define.SourceHeader with - | "" -> () - | s -> f s \ No newline at end of file diff --git a/src/generators/gctx_todo.ml b/src/generators/gctx_todo.ml new file mode 100644 index 00000000000..be907f03cd0 --- /dev/null +++ b/src/generators/gctx_todo.ml @@ -0,0 +1,9 @@ +open Define + +let get_es_version defines = + try int_of_string (Define.defined_value defines Define.JsEs) with _ -> 0 + +let map_source_header defines f = + match Define.defined_value_safe defines Define.SourceHeader with + | "" -> () + | s -> f s \ No newline at end of file diff --git a/src/generators/genjs.ml b/src/generators/genjs.ml index a290498f327..7aca7a50f1f 100644 --- a/src/generators/genjs.ml +++ b/src/generators/genjs.ml @@ -21,11 +21,11 @@ open Globals open Ast open Type open Error -open Common +open Gctx open JsSourcemap type ctx = { - com : Common.context; + com : Gctx.t; buf : Rbuffer.t; mutable chan : out_channel option; packages : (string list,unit) Hashtbl.t; @@ -46,7 +46,6 @@ type ctx = { mutable separator : bool; mutable found_expose : bool; mutable catch_vars : texpr list; - mutable deprecation_context : DeprecationCheck.deprecation_context; } type object_store = { @@ -90,7 +89,7 @@ let es5kwds = [ let setup_kwds com = Hashtbl.reset kwds; - let es_version = get_es_version com in + let es_version = Gctx_todo.get_es_version com.defines in let lst = if es_version >= 5 then es5kwds else es3kwds in List.iter (fun s -> Hashtbl.add kwds s ()) lst @@ -148,8 +147,8 @@ let module_field_expose_path mpath f = with Not_found -> (dot_path mpath) ^ "." ^ f.cf_name -let has_feature ctx = Common.has_feature ctx.com -let add_feature ctx = Common.add_feature ctx.com +let has_feature ctx = Gctx.has_feature ctx.com +let add_feature ctx = Gctx.add_feature ctx.com let unsupported p = abort "This expression cannot be compiled to Javascript" p @@ -367,24 +366,6 @@ let rec gen_call ctx e el in_value = | _ -> abort "js.Lib.getOriginalException can only be called inside a catch block" e.epos ) - | TIdent "__new__", args -> - print_deprecation_message ctx.deprecation_context "__new__ is deprecated, use js.Syntax.construct instead" e.epos; - gen_syntax ctx "construct" args e.epos - | TIdent "__js__", args -> - print_deprecation_message ctx.deprecation_context "__js__ is deprecated, use js.Syntax.code instead" e.epos; - gen_syntax ctx "code" args e.epos - | TIdent "__instanceof__", args -> - print_deprecation_message ctx.deprecation_context "__instanceof__ is deprecated, use js.Syntax.instanceof instead" e.epos; - gen_syntax ctx "instanceof" args e.epos - | TIdent "__typeof__", args -> - print_deprecation_message ctx.deprecation_context "__typeof__ is deprecated, use js.Syntax.typeof instead" e.epos; - gen_syntax ctx "typeof" args e.epos - | TIdent "__strict_eq__" , args -> - print_deprecation_message ctx.deprecation_context "__strict_eq__ is deprecated, use js.Syntax.strictEq instead" e.epos; - gen_syntax ctx "strictEq" args e.epos - | TIdent "__strict_neq__" , args -> - print_deprecation_message ctx.deprecation_context "__strict_neq__ is deprecated, use js.Syntax.strictNeq instead" e.epos; - gen_syntax ctx "strictNeq" args e.epos | TIdent "__define_feature__", [_;e] -> gen_expr ctx e | TIdent "__feature__", { eexpr = TConst (TString f) } :: eif :: eelse -> @@ -550,13 +531,13 @@ and gen_expr ctx e = print ctx ",$bind($_,$_%s))" (if Meta.has Meta.SelfCall f.cf_meta then "" else (field f.cf_name))) | TEnumIndex x -> gen_value ctx x; - if not (Common.defined ctx.com Define.JsEnumsAsArrays) then + if not (Gctx.defined ctx.com Define.JsEnumsAsArrays) then print ctx "._hx_index" else print ctx "[1]" | TEnumParameter (x,f,i) -> gen_value ctx x; - if not (Common.defined ctx.com Define.JsEnumsAsArrays) then + if not (Gctx.defined ctx.com Define.JsEnumsAsArrays) then let fname = (match f.ef_type with TFun((args,_)) -> let fname,_,_ = List.nth args i in fname | _ -> die "" __LOC__ ) in print ctx ".%s" (ident fname) else @@ -1031,7 +1012,7 @@ and gen_syntax ctx meth args pos = ) args in - Codegen.interpolate_code ctx.com code args (spr ctx) (gen_value ctx) code_pos + Codegen.interpolate_code ctx.com.error code args (spr ctx) (gen_value ctx) code_pos end | "plainCode", [code] -> let code = @@ -1147,7 +1128,6 @@ let can_gen_class_field ctx = function is_physical_field f let gen_class_field ctx c f = - ctx.deprecation_context <- {ctx.deprecation_context with field_meta = f.cf_meta}; check_field_name c f; match f.cf_expr with | None -> @@ -1473,7 +1453,6 @@ let generate_class_es6 ctx c = let generate_class ctx c = ctx.current <- c; - ctx.deprecation_context <- {ctx.deprecation_context with class_meta = c.cl_meta}; ctx.id_counter <- 0; (match c.cl_path with | [],"Function" -> abort "This class redefine a native one" c.cl_pos @@ -1496,7 +1475,7 @@ let generate_enum ctx e = else generate_package_create ctx e.e_path; print ctx "%s = " p; - let as_objects = not (Common.defined ctx.com Define.JsEnumsAsArrays) in + let as_objects = not (Gctx.defined ctx.com Define.JsEnumsAsArrays) in (if as_objects then print ctx "$hxEnums[\"%s\"] = " dotp else if has_feature ctx "Type.resolveEnum" then @@ -1653,7 +1632,7 @@ let set_current_class ctx c = let alloc_ctx com es_version = let smap = - if com.debug || Common.defined com Define.JsSourceMap || Common.defined com Define.SourceMap then + if com.debug || Gctx.defined com Define.JsSourceMap || Gctx.defined com Define.SourceMap then Some { source_last_pos = { file = 0; line = 0; col = 0}; print_comma = false; @@ -1673,10 +1652,10 @@ let alloc_ctx com es_version = chan = None; packages = Hashtbl.create 0; smap = smap; - js_modern = not (Common.defined com Define.JsClassic); - js_flatten = not (Common.defined com Define.JsUnflatten); - has_resolveClass = Common.has_feature com "Type.resolveClass"; - has_interface_check = Common.has_feature com "js.Boot.__interfLoop"; + js_modern = not (Gctx.defined com Define.JsClassic); + js_flatten = not (Gctx.defined com Define.JsUnflatten); + has_resolveClass = Gctx.has_feature com "Type.resolveClass"; + has_interface_check = Gctx.has_feature com "js.Boot.__interfLoop"; es_version = es_version; statics = []; inits = []; @@ -1689,7 +1668,6 @@ let alloc_ctx com es_version = separator = false; found_expose = false; catch_vars = []; - deprecation_context = DeprecationCheck.create_context com; } in ctx.type_accessor <- (fun t -> @@ -1714,22 +1692,22 @@ let gen_single_expr ctx e expr = ctx.id_counter <- 0; str -let generate com = - (match com.js_gen with +let generate js_gen com = + (match js_gen with | Some g -> g() | None -> - let es_version = get_es_version com in + let es_version = Gctx_todo.get_es_version com.defines in if es_version >= 6 then ES6Ctors.rewrite_ctors com; let ctx = alloc_ctx com es_version in - Codegen.map_source_header com (fun s -> print ctx "// %s\n" s); + Gctx_todo.map_source_header com.defines (fun s -> print ctx "// %s\n" s); if has_feature ctx "Class" || has_feature ctx "Type.getClassName" then add_feature ctx "js.Boot.isClass"; if has_feature ctx "Enum" || has_feature ctx "Type.getEnumName" then add_feature ctx "js.Boot.isEnum"; - let nodejs = Common.raw_defined com "nodejs" in + let nodejs = Gctx.raw_defined com "nodejs" in setup_kwds com; @@ -1792,7 +1770,7 @@ let generate com = | _ -> () ) include_files; - let defined_global_value = Common.defined_value_safe com Define.JsGlobal in + let defined_global_value = Gctx.defined_value_safe com Define.JsGlobal in let defined_global = defined_global_value <> "" in @@ -1813,7 +1791,7 @@ let generate com = ) in let closureArgs = [var_global] in - let closureArgs = if (anyExposed && not (Common.defined com Define.ShallowExpose)) then + let closureArgs = if (anyExposed && not (Gctx.defined com Define.ShallowExpose)) then var_exports :: closureArgs else closureArgs @@ -1829,7 +1807,7 @@ let generate com = (* Add node globals to pseudo-keywords, so they are not shadowed by local vars *) List.iter (fun s -> Hashtbl.replace kwds2 s ()) [ "global"; "process"; "__filename"; "__dirname"; "module" ]; - if (anyExposed && ((Common.defined com Define.ShallowExpose) || not ctx.js_modern)) then ( + if (anyExposed && ((Gctx.defined com Define.ShallowExpose) || not ctx.js_modern)) then ( print ctx "var %s = %s" (fst var_exports) (snd var_exports); ctx.separator <- true; newline ctx @@ -1870,7 +1848,7 @@ let generate com = if (not ctx.js_modern) && (ctx.es_version < 5) then spr ctx "var console = $global.console || {log:function(){}};\n"; - let enums_as_objects = not (Common.defined com Define.JsEnumsAsArrays) in + let enums_as_objects = not (Gctx.defined com Define.JsEnumsAsArrays) in (* TODO: fix $estr *) let vars = [] in @@ -1989,7 +1967,7 @@ let generate com = newline ctx; end; - if (anyExposed && (Common.defined com Define.ShallowExpose)) then ( + if (anyExposed && (Gctx.defined com Define.ShallowExpose)) then ( List.iter (fun f -> print ctx "var %s = $hx_exports%s" f.os_name (path_to_brackets f.os_name); ctx.separator <- true; diff --git a/src/generators/genlua.ml b/src/generators/genlua.ml index cab664cb4d6..99dc036cc1e 100644 --- a/src/generators/genlua.ml +++ b/src/generators/genlua.ml @@ -458,7 +458,7 @@ and gen_call ctx e el = | TIdent "__lua__", [{ eexpr = TConst (TString code) }] -> spr ctx (String.concat "\n" (ExtString.String.nsplit code "\r\n")) | TIdent "__lua__", { eexpr = TConst (TString code); epos = p } :: tl -> - Codegen.interpolate_code ctx.com code tl (spr ctx) (gen_expr ctx) p + Codegen.interpolate_code ctx.com.error code tl (spr ctx) (gen_expr ctx) p | TIdent "__type__", [o] -> spr ctx "type"; gen_paren ctx [o]; @@ -2009,7 +2009,7 @@ let transform_multireturn ctx = function let generate com = let ctx = alloc_ctx com in - Codegen.map_source_header com (fun s -> print ctx "-- %s\n" s); + Gctx_todo.map_source_header com.defines (fun s -> print ctx "-- %s\n" s); if has_feature ctx "Class" || has_feature ctx "Type.getClassName" then add_feature ctx "lua.Boot.isClass"; if has_feature ctx "Enum" || has_feature ctx "Type.getEnumName" then add_feature ctx "lua.Boot.isEnum"; @@ -2214,7 +2214,7 @@ let generate com = println ctx "return _hx_exports"; (match ctx.smap with - | Some smap -> write_mappings ctx.com smap "" + | Some smap -> write_mappings (Common.to_gctx ctx.com) smap "" | None -> try Sys.remove (com.file ^ ".map") with _ -> ()); let ch = open_out_bin com.file in diff --git a/src/generators/genphp7.ml b/src/generators/genphp7.ml index c89e41b3e55..431d044aa58 100644 --- a/src/generators/genphp7.ml +++ b/src/generators/genphp7.ml @@ -2021,7 +2021,7 @@ class code_writer (ctx:php_generator_context) hx_type_path php_name = | "__php__" -> (match expr.eexpr with | TConst (TString php) -> - Codegen.interpolate_code ctx.pgc_common php args self#write self#write_expr self#pos + Codegen.interpolate_code ctx.pgc_common.error php args self#write self#write_expr self#pos | _ -> fail self#pos __LOC__ ) | "__call__" -> @@ -2445,7 +2445,7 @@ class code_writer (ctx:php_generator_context) hx_type_path php_name = ) args in - Codegen.interpolate_code ctx.pgc_common php args self#write self#write_expr self#pos + Codegen.interpolate_code ctx.pgc_common.error php args self#write self#write_expr self#pos | _ -> ctx.pgc_common.error "First argument of php.Syntax.code() must be a constant string." self#pos (** Writes error suppression operator (for `php.Syntax.suppress()`) @@ -3045,7 +3045,7 @@ class virtual type_builder ctx (wrapper:type_wrapper) = writer#indent 0; writer#write_line " writer#write_line (" * " ^ s)); + Gctx_todo.map_source_header ctx.pgc_common.defines (fun s -> writer#write_line (" * " ^ s)); if ctx.pgc_common.debug then writer#write_line (" * Haxe source file: " ^ self#get_source_file); writer#write_line " */"; writer#write "\n"; diff --git a/src/generators/genpy.ml b/src/generators/genpy.ml index c170bd436ca..1acf161185c 100644 --- a/src/generators/genpy.ml +++ b/src/generators/genpy.ml @@ -1491,7 +1491,7 @@ module Printer = struct | ("python_Syntax.code"),({ eexpr = TConst (TString code) } as ecode) :: tl -> let buf = Buffer.create 0 in let interpolate () = - Codegen.interpolate_code pctx.pc_com code tl (Buffer.add_string buf) (fun e -> Buffer.add_string buf (print_expr pctx e)) ecode.epos + Codegen.interpolate_code pctx.pc_com.error code tl (Buffer.add_string buf) (fun e -> Buffer.add_string buf (print_expr pctx e)) ecode.epos in let old = pctx.pc_com.error_ext in pctx.pc_com.error_ext <- (fun err -> raise (Error.Fatal_error err)); @@ -2427,7 +2427,7 @@ module Generator = struct let run com = Transformer.init com; let ctx = mk_context com in - Codegen.map_source_header com (fun s -> print ctx "# %s\n# coding: utf-8\n" s); + Gctx_todo.map_source_header com.defines (fun s -> print ctx "# %s\n# coding: utf-8\n" s); if has_feature ctx "closure_Array" || has_feature ctx "closure_String" then spr ctx "from functools import partial as _hx_partial\n"; spr ctx "import sys\n"; diff --git a/src/generators/hl2c.ml b/src/generators/hl2c.ml index 2da597ebcc1..b716ee5ebc1 100644 --- a/src/generators/hl2c.ml +++ b/src/generators/hl2c.ml @@ -345,7 +345,7 @@ let short_digest str = let open_file ctx file = if ctx.curfile <> "" then close_file ctx; if file <> "hlc.json" then - Gctx.map_source_header ctx.gcon (fun s -> define ctx (sprintf "// %s" s)); + Gctx_todo.map_source_header ctx.gcon.defines (fun s -> define ctx (sprintf "// %s" s)); ctx.curfile <- file; ctx.fun_index <- 0; ctx.file_prefix <- (short_digest file) ^ "_" diff --git a/src/generators/jsSourcemap.ml b/src/generators/jsSourcemap.ml index f44a2029162..31e7a48eea4 100644 --- a/src/generators/jsSourcemap.ml +++ b/src/generators/jsSourcemap.ml @@ -131,7 +131,7 @@ let handle_newlines smap str = loop 0 ) smap -let write_mappings (com : Common.context) smap source_path_prefix = +let write_mappings (com : Gctx.t) smap source_path_prefix = let basefile = Filename.basename com.file in let channel = open_out_bin (com.file ^ ".map") in let sources = DynArray.to_list smap.sources in @@ -145,7 +145,7 @@ let write_mappings (com : Common.context) smap source_path_prefix = output_string channel ("\"sources\":[" ^ (String.concat "," (List.map (fun s -> "\"" ^ source_path_prefix ^ to_url s ^ "\"") sources)) ^ "],\n"); - if Common.defined com Define.SourceMapContent then begin + if Gctx.defined com Define.SourceMapContent then begin output_string channel ("\"sourcesContent\":[" ^ (String.concat "," (List.map (fun s -> try "\"" ^ StringHelper.s_escape (Std.input_file ~bin:true s) ^ "\"" with _ -> "null") sources)) ^ "],\n"); diff --git a/src/macro/macroApi.ml b/src/macro/macroApi.ml index c18b0bf1a55..79adeacd7bb 100644 --- a/src/macro/macroApi.ml +++ b/src/macro/macroApi.ml @@ -2013,7 +2013,7 @@ let macro_api ccom get_api = "set_custom_js_generator", vfun1 (fun f -> let f = prepare_callback f 1 in (get_api()).set_js_generator (fun js_ctx -> - let com = ccom() in + let com = Common.to_gctx (ccom()) in Genjs.setup_kwds com; let api = encode_obj [ "outputFile", encode_string com.file; @@ -2028,10 +2028,10 @@ let macro_api ccom get_api = vbool (Hashtbl.mem Genjs.kwds (decode_string v)) ); "hasFeature", vfun1 (fun v -> - vbool (Common.has_feature com (decode_string v)) + vbool (Gctx.has_feature com (decode_string v)) ); "addFeature", vfun1 (fun v -> - Common.add_feature com (decode_string v); + Gctx.add_feature com (decode_string v); vnull ); "quoteString", vfun1 (fun v -> diff --git a/src/typing/macroContext.ml b/src/typing/macroContext.ml index f83d5fe8921..5bb19058c6f 100644 --- a/src/typing/macroContext.ml +++ b/src/typing/macroContext.ml @@ -211,7 +211,7 @@ let make_macro_com_api com mcom p = set_js_generator = (fun gen -> com.js_gen <- Some (fun() -> Path.mkdir_from_path com.file; - let js_ctx = Genjs.alloc_ctx com (get_es_version com) in + let js_ctx = Genjs.alloc_ctx (Common.to_gctx com) (Gctx_todo.get_es_version com.defines) in let t = macro_timer com ["jsGenerator"] in gen js_ctx; t() From dd6f2bbb20bfa5e4d096e999855e1017e3100ce7 Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 09:44:04 +0100 Subject: [PATCH 04/13] genlua --- src/compiler/generate.ml | 4 ++- src/generators/genlua.ml | 58 ++++++++++++++++++----------------- src/generators/jsSourcemap.ml | 1 - 3 files changed, 33 insertions(+), 30 deletions(-) diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index ec827842d10..d47ce42cf14 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -182,7 +182,9 @@ let generate ctx tctx ext actx = Genjs.generate com.js_gen (Common.to_gctx com) ),"js" | Lua -> - Genlua.generate,"lua" + (fun com -> + Genlua.generate (Common.to_gctx com) + ),"lua" | Php -> Genphp7.generate,"php" | Cpp -> diff --git a/src/generators/genlua.ml b/src/generators/genlua.ml index 99dc036cc1e..9107e10bf41 100644 --- a/src/generators/genlua.ml +++ b/src/generators/genlua.ml @@ -23,7 +23,7 @@ open Extlib_leftovers open Ast open Type -open Common +open Gctx open ExtList open Error open JsSourcemap @@ -31,7 +31,7 @@ open JsSourcemap type pos = Globals.pos type ctx = { - com : Common.context; + com : Gctx.t; buf : Buffer.t; packages : (string list,unit) Hashtbl.t; smap : sourcemap option; @@ -137,8 +137,8 @@ let static_field c s = | "length" | "name" when not (has_class_flag c CExtern) || Meta.has Meta.HxGen c.cl_meta-> "._hx" ^ s | s -> field s -let has_feature ctx = Common.has_feature ctx.com -let add_feature ctx = Common.add_feature ctx.com +let has_feature ctx = Gctx.has_feature ctx.com +let add_feature ctx = Gctx.add_feature ctx.com let temp ctx = ctx.id_counter <- ctx.id_counter + 1; @@ -1886,7 +1886,7 @@ let generate_type_forward ctx = function let alloc_ctx com = let smap = - if com.debug || Common.defined com Define.SourceMap then + if com.debug || Gctx.defined com Define.SourceMap then Some { source_last_pos = { file = 0; line = 0; col = 0}; print_comma = false; @@ -1919,10 +1919,10 @@ let alloc_ctx com = type_accessor = (fun _ -> Globals.die "" __LOC__); separator = false; found_expose = false; - lua_jit = Common.defined com Define.LuaJit; - lua_vanilla = Common.defined com Define.LuaVanilla; + lua_jit = Gctx.defined com Define.LuaJit; + lua_vanilla = Gctx.defined com Define.LuaVanilla; lua_ver = try - float_of_string (Common.defined_value com Define.LuaVer) + float_of_string (Gctx.defined_value com Define.LuaVer) with | Not_found -> 5.2; } in ctx.type_accessor <- (fun t -> @@ -2019,20 +2019,22 @@ let generate com = print ctx "%s\n" file_content; in + let find_file f = (com.class_paths#find_file f).file in + (* base table-to-array helpers and metatables *) - print_file (Common.find_file com "lua/_lua/_hx_tab_array.lua"); + print_file (find_file "lua/_lua/_hx_tab_array.lua"); (* base lua "toString" functionality for haxe objects*) - print_file (Common.find_file com "lua/_lua/_hx_tostring.lua"); + print_file (find_file "lua/_lua/_hx_tostring.lua"); (* base lua metatables for prototypes, inheritance, etc. *) - print_file (Common.find_file com "lua/_lua/_hx_anon.lua"); + print_file (find_file "lua/_lua/_hx_anon.lua"); (* Helpers for creating metatables from prototypes *) - print_file (Common.find_file com "lua/_lua/_hx_objects.lua"); + print_file (find_file "lua/_lua/_hx_objects.lua"); (* base runtime class stubs for haxe value types (Int, Float, etc) *) - print_file (Common.find_file com "lua/_lua/_hx_classes.lua"); + print_file (find_file "lua/_lua/_hx_classes.lua"); let include_files = List.rev com.include_files in List.iter (fun file -> @@ -2122,18 +2124,18 @@ let generate com = (* If bit ops are manually imported include the haxe wrapper for them *) if has_feature ctx "use._bitop" then begin - print_file (Common.find_file com "lua/_lua/_hx_bit.lua"); + print_file (find_file "lua/_lua/_hx_bit.lua"); end; (* integer clamping is always required, and will use bit ops if available *) - print_file (Common.find_file com "lua/_lua/_hx_bit_clamp.lua"); + print_file (find_file "lua/_lua/_hx_bit_clamp.lua"); (* Array is required, always patch it *) println ctx "_hx_array_mt.__index = Array.prototype"; newline ctx; (* Functions to support auto-run of libuv loop *) - print_file (Common.find_file com "lua/_lua/_hx_luv.lua"); + print_file (find_file "lua/_lua/_hx_luv.lua"); let b = open_block ctx in (* Localize init variables inside a do-block *) @@ -2148,45 +2150,45 @@ let generate com = newline ctx; if has_feature ctx "use._hx_bind" then begin - print_file (Common.find_file com "lua/_lua/_hx_bind.lua"); + print_file (find_file "lua/_lua/_hx_bind.lua"); end; if has_feature ctx "use._hx_staticToInstance" then begin - print_file (Common.find_file com "lua/_lua/_hx_static_to_instance.lua"); + print_file (find_file "lua/_lua/_hx_static_to_instance.lua"); end; if has_feature ctx "use._hx_funcToField" then begin - print_file (Common.find_file com "lua/_lua/_hx_func_to_field.lua"); + print_file (find_file "lua/_lua/_hx_func_to_field.lua"); end; if has_feature ctx "Math.random" then begin - print_file (Common.find_file com "lua/_lua/_hx_random_init.lua"); + print_file (find_file "lua/_lua/_hx_random_init.lua"); end; if has_feature ctx "use._hx_print" then - print_file (Common.find_file com "lua/_lua/_hx_print.lua"); + print_file (find_file "lua/_lua/_hx_print.lua"); if has_feature ctx "use._hx_apply_self" then begin - print_file (Common.find_file com "lua/_lua/_hx_apply_self.lua"); + print_file (find_file "lua/_lua/_hx_apply_self.lua"); end; if has_feature ctx "use._hx_box_mr" then begin - print_file (Common.find_file com "lua/_lua/_hx_box_mr.lua"); + print_file (find_file "lua/_lua/_hx_box_mr.lua"); end; if has_feature ctx "use._hx_table" then begin - print_file (Common.find_file com "lua/_lua/_hx_table.lua"); + print_file (find_file "lua/_lua/_hx_table.lua"); end; if has_feature ctx "use._hx_wrap_if_string_field" then begin - print_file (Common.find_file com "lua/_lua/_hx_wrap_if_string_field.lua"); + print_file (find_file "lua/_lua/_hx_wrap_if_string_field.lua"); end; if has_feature ctx "use._hx_dyn_add" then begin - print_file (Common.find_file com "lua/_lua/_hx_dyn_add.lua"); + print_file (find_file "lua/_lua/_hx_dyn_add.lua"); end; - print_file (Common.find_file com "lua/_lua/_hx_handle_error.lua"); + print_file (find_file "lua/_lua/_hx_handle_error.lua"); println ctx "_hx_static_init();"; @@ -2214,7 +2216,7 @@ let generate com = println ctx "return _hx_exports"; (match ctx.smap with - | Some smap -> write_mappings (Common.to_gctx ctx.com) smap "" + | Some smap -> write_mappings ctx.com smap "" | None -> try Sys.remove (com.file ^ ".map") with _ -> ()); let ch = open_out_bin com.file in diff --git a/src/generators/jsSourcemap.ml b/src/generators/jsSourcemap.ml index 31e7a48eea4..01aad6ba3fd 100644 --- a/src/generators/jsSourcemap.ml +++ b/src/generators/jsSourcemap.ml @@ -19,7 +19,6 @@ open Extlib_leftovers open Globals open Type -open Common type sourcemap = { sources : (string) DynArray.t; From bdaf973ac72d076381784b7220d39dde4c80d33f Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 09:53:54 +0100 Subject: [PATCH 05/13] re-port has_feature --- src/generators/gctx.ml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/generators/gctx.ml b/src/generators/gctx.ml index 69d1ffaccf3..0446919a088 100644 --- a/src/generators/gctx.ml +++ b/src/generators/gctx.ml @@ -74,9 +74,15 @@ let rec has_feature gctx f = (match List.find (fun t -> t_path t = path && not (Meta.has Meta.RealPath (t_infos t).mt_meta)) gctx.types with | t when field = "*" -> not (has_dce gctx) || - (match t with TAbstractDecl a -> Meta.has Meta.ValueUsed a.a_meta | _ -> Meta.has Meta.Used (t_infos t).mt_meta) + begin match t with + | TClassDecl c -> + has_class_flag c CUsed; + | TAbstractDecl a -> + Meta.has Meta.ValueUsed a.a_meta + | _ -> Meta.has Meta.Used (t_infos t).mt_meta + end; | TClassDecl c when (has_class_flag c CExtern) && (gctx.platform <> Js || cl <> "Array" && cl <> "Math") -> - not (has_dce gctx) || Meta.has Meta.Used (try PMap.find field c.cl_statics with Not_found -> PMap.find field c.cl_fields).cf_meta + not (has_dce gctx) || has_class_field_flag (try PMap.find field c.cl_statics with Not_found -> PMap.find field c.cl_fields) CfUsed | TClassDecl c -> PMap.exists field c.cl_statics || PMap.exists field c.cl_fields | _ -> From a32fe03c8dfe584b275967603e4e261c444d5b6e Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 10:00:44 +0100 Subject: [PATCH 06/13] neko --- src/codegen/codegen.ml | 5 ++--- src/compiler/generate.ml | 4 +++- src/context/common.ml | 1 + src/generators/gctx.ml | 1 + src/generators/genneko.ml | 23 ++++++++++++----------- src/generators/genpy.ml | 3 ++- 6 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/codegen/codegen.ml b/src/codegen/codegen.ml index 5dbd0b4f289..9c0881c43ce 100644 --- a/src/codegen/codegen.ml +++ b/src/codegen/codegen.ml @@ -418,13 +418,12 @@ end Build a default safe-cast expression : { var $t = ; if( Std.is($t,) ) $t else throw "Class cast error"; } *) -let default_cast ?(vtmp="$t") com e texpr t p = - let api = com.basic in +let default_cast ?(vtmp="$t") api std e texpr t p = let vtmp = alloc_var VGenerated vtmp e.etype e.epos in let var = mk (TVar (vtmp,Some e)) api.tvoid p in let vexpr = mk (TLocal vtmp) e.etype p in let texpr = Texpr.Builder.make_typeexpr texpr p in - let is = Texpr.Builder.resolve_and_make_static_call com.std "isOfType" [vexpr;texpr] p in + let is = Texpr.Builder.resolve_and_make_static_call std "isOfType" [vexpr;texpr] p in let enull = Texpr.Builder.make_null vexpr.etype p in let eop = Texpr.Builder.binop OpEq vexpr enull api.tbool p in let echeck = Texpr.Builder.binop OpBoolOr is eop api.tbool p in diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index d47ce42cf14..6329507bd74 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -176,7 +176,9 @@ let generate ctx tctx ext actx = in Genswf.generate header,"swf" | Neko -> - Genneko.generate,"neko" + (fun com -> + Genneko.generate com.neko_lib_paths (Common.to_gctx com) + ),"neko" | Js -> (fun com -> Genjs.generate com.js_gen (Common.to_gctx com) diff --git a/src/context/common.ml b/src/context/common.ml index f6008fd5ba8..36c16813b36 100644 --- a/src/context/common.ml +++ b/src/context/common.ml @@ -450,6 +450,7 @@ let to_gctx com = { | Flash -> (com.native_libs.swf_libs :> NativeLibraries.native_library_base list) | _ -> []); include_files = com.include_files; + std = com.std; } let enter_stage com stage = diff --git a/src/generators/gctx.ml b/src/generators/gctx.ml index 0446919a088..04c17b55b32 100644 --- a/src/generators/gctx.ml +++ b/src/generators/gctx.ml @@ -29,6 +29,7 @@ type t = { resources : (string,string) Hashtbl.t; native_libs : NativeLibraries.native_library_base list; include_files : (string * string) list; + std : tclass; (* TODO: I would prefer to not have this here, have to check default_cast *) } let defined com s = diff --git a/src/generators/genneko.ml b/src/generators/genneko.ml index 29a43826933..15295a513da 100644 --- a/src/generators/genneko.ml +++ b/src/generators/genneko.ml @@ -21,11 +21,11 @@ open Ast open Globals open Type open Nast -open Common +open Gctx type context = { version : int; - com : Common.context; + com : Gctx.t; packages : (string list, unit) Hashtbl.t; globals : (string list * string, string) Hashtbl.t; mutable curglobal : int; @@ -50,7 +50,7 @@ let pos ctx p = try Hashtbl.find files p.pfile with Not_found -> - let path = (match Common.defined ctx.com Common.Define.AbsolutePath with + let path = (match Gctx.defined ctx.com Define.AbsolutePath with | true -> if (Filename.is_relative p.pfile) then Filename.concat (Sys.getcwd()) p.pfile else p.pfile @@ -371,7 +371,7 @@ and gen_expr ctx e = | TCast (e,None) -> gen_expr ctx e | TCast (e1,Some t) -> - gen_expr ctx (Codegen.default_cast ~vtmp:"@tmp" ctx.com e1 t e.etype e.epos) + gen_expr ctx (Codegen.default_cast ~vtmp:"@tmp" ctx.com.basic ctx.com.std e1 t e.etype e.epos) | TIdent s -> ident p s | TSwitch {switch_subject = e;switch_cases = cases;switch_default = eo} -> @@ -771,19 +771,20 @@ let build ctx types = let vars = List.concat (List.map (gen_static_vars ctx) types) in packs @ methods @ boot :: names @ inits @ vars -let generate com = +let generate neko_lib_paths com = Hashtbl.clear files; - let ctx = new_context com (if Common.defined com Define.NekoV1 then 1 else 2) false in + let ctx = new_context com (if Gctx.defined com Define.NekoV1 then 1 else 2) false in let libs = (EBlock - (if Common.defined com Define.NekoNoHaxelibPaths then [] - else generate_libs_init com.neko_lib_paths), + (if Gctx.defined com Define.NekoNoHaxelibPaths then [] + else generate_libs_init neko_lib_paths), { psource = "
"; pline = 1; } ) in let el = build ctx com.types in let emain = (match com.main.main_expr with None -> [] | Some e -> [gen_expr ctx e]) in let e = (EBlock ((header()) @ libs :: el @ emain), null_pos) in - let source = Common.defined com Define.NekoSource in - let use_nekoc = Common.defined com Define.UseNekoc in + let source = Gctx.defined com Define.NekoSource in + let use_nekoc = Gctx.defined com Define.UseNekoc in + let find_file f = (com.class_paths#find_file f).file in if not use_nekoc then begin try Path.mkdir_from_path com.file; @@ -791,7 +792,7 @@ let generate com = Nbytecode.write ch (Ncompile.compile ctx.version e); IO.close_out ch; with Ncompile.Error (msg,pos) -> - let pfile = Common.find_file com pos.psource in + let pfile = find_file pos.psource in let rec loop p = let pp = { pfile = pfile; pmin = p; pmax = p; } in if Lexer.get_error_line pp >= pos.pline then diff --git a/src/generators/genpy.ml b/src/generators/genpy.ml index 1acf161185c..cc2e8bffc2a 100644 --- a/src/generators/genpy.ml +++ b/src/generators/genpy.ml @@ -955,7 +955,8 @@ module Transformer = struct let r = { a_expr with eexpr = TArrayDecl exprs } in lift_expr ae.a_next_id ~blocks:blocks r | (is_value, TCast(e1,Some mt)) -> - let e = Codegen.default_cast ~vtmp:(ae.a_next_id()) (match !como with Some com -> com | None -> die "" __LOC__) e1 mt ae.a_expr.etype ae.a_expr.epos in + let com = (match !como with Some com -> com | None -> die "" __LOC__) in + let e = Codegen.default_cast ~vtmp:(ae.a_next_id()) com.basic com.std e1 mt ae.a_expr.etype ae.a_expr.epos in transform_expr ae.a_next_id ~is_value:is_value e | (is_value, TCast(e,None)) -> let e = trans is_value [] e in From bffb7551a5b16aff77f4595d5b99c5f97b18e1dc Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 13:56:29 +0100 Subject: [PATCH 07/13] python --- src/compiler/generate.ml | 4 +++- src/generators/genpy.ml | 18 ++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index 6329507bd74..8b87deb157c 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -196,7 +196,9 @@ let generate ctx tctx ext actx = Genjvm.generate actx.jvm_flag (Common.to_gctx com) ),"jvm" | Python -> - Genpy.generate,"python" + (fun com -> + Genpy.generate (Common.to_gctx com) + ),"python" | Hl -> (fun com -> Genhl.generate (Common.to_gctx com) diff --git a/src/generators/genpy.ml b/src/generators/genpy.ml index cc2e8bffc2a..95c162cd63b 100644 --- a/src/generators/genpy.ml +++ b/src/generators/genpy.ml @@ -21,7 +21,7 @@ open Globals open Ast open Error open Type -open Common +open Gctx open Texpr.Builder module Utils = struct @@ -1000,12 +1000,12 @@ module Printer = struct pc_indent : string; pc_next_anon_func : unit -> string; pc_debug : bool; - pc_com : Common.context; + pc_com : Gctx.t; } - let has_feature pctx = Common.has_feature pctx.pc_com + let has_feature pctx = Gctx.has_feature pctx.pc_com - let add_feature pctx = Common.add_feature pctx.pc_com + let add_feature pctx = Gctx.add_feature pctx.pc_com let create_context = let n = ref (-1) in @@ -1494,9 +1494,7 @@ module Printer = struct let interpolate () = Codegen.interpolate_code pctx.pc_com.error code tl (Buffer.add_string buf) (fun e -> Buffer.add_string buf (print_expr pctx e)) ecode.epos in - let old = pctx.pc_com.error_ext in - pctx.pc_com.error_ext <- (fun err -> raise (Error.Fatal_error err)); - Std.finally (fun() -> pctx.pc_com.error_ext <- old) interpolate (); + interpolate (); Buffer.contents buf | ("python_Syntax._pythonCode"), [e] -> print_expr pctx e @@ -1674,7 +1672,7 @@ end module Generator = struct type context = { - com : Common.context; + com : Gctx.t; buf : Buffer.t; packages : (string,int) Hashtbl.t; mutable static_inits : (unit -> unit) list; @@ -1684,8 +1682,8 @@ module Generator = struct print_time : float; } - let has_feature ctx = Common.has_feature ctx.com - let add_feature ctx = Common.add_feature ctx.com + let has_feature ctx = Gctx.has_feature ctx.com + let add_feature ctx = Gctx.add_feature ctx.com type class_field_infos = { cfd_fields : string list; From f2deea9501e3e4ef983755d1da2904ede583e106 Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 14:19:42 +0100 Subject: [PATCH 08/13] swf --- src/compiler/generate.ml | 4 +- src/context/common.ml | 21 ---------- src/generators/genswf.ml | 85 +++++++++++++++++++++++++-------------- src/generators/genswf9.ml | 20 ++++----- 4 files changed, 67 insertions(+), 63 deletions(-) diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index 8b87deb157c..c398720bbc0 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -174,7 +174,9 @@ let generate ctx tctx ext actx = with Not_found -> None in - Genswf.generate header,"swf" + (fun com -> + Genswf.generate header com.Common.native_libs.swf_libs com.Common.flash_version (Common.to_gctx com) + ),"swf" | Neko -> (fun com -> Genneko.generate com.neko_lib_paths (Common.to_gctx com) diff --git a/src/context/common.ml b/src/context/common.ml index 36c16813b36..45ddec71f30 100644 --- a/src/context/common.ml +++ b/src/context/common.ml @@ -944,27 +944,6 @@ let flash_versions = List.map (fun v -> v, string_of_int maj ^ (if min = 0 then "" else "_" ^ string_of_int min) ) [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;18.0;19.0;20.0;21.0;22.0;23.0;24.0;25.0;26.0;27.0;28.0;29.0;31.0;32.0] -let flash_version_tag = function - | 6. -> 6 - | 7. -> 7 - | 8. -> 8 - | 9. -> 9 - | 10. | 10.1 -> 10 - | 10.2 -> 11 - | 10.3 -> 12 - | 11. -> 13 - | 11.1 -> 14 - | 11.2 -> 15 - | 11.3 -> 16 - | 11.4 -> 17 - | 11.5 -> 18 - | 11.6 -> 19 - | 11.7 -> 20 - | 11.8 -> 21 - | 11.9 -> 22 - | v when v >= 12.0 && float_of_int (int_of_float v) = v -> int_of_float v + 11 - | v -> failwith ("Invalid SWF version " ^ string_of_float v) - let update_platform_config com = match com.platform with | CustomTarget _ -> diff --git a/src/generators/genswf.ml b/src/generators/genswf.ml index db182a137c0..8aed80733f9 100644 --- a/src/generators/genswf.ml +++ b/src/generators/genswf.ml @@ -21,7 +21,7 @@ open As3hl open ExtString open Type open Error -open Common +open Gctx open Ast open Globals open NativeLibraries @@ -32,14 +32,35 @@ let tag ?(ext=false) d = { tdata = d; } -let convert_header com (w,h,fps,bg) = +let flash_version_tag = function + | 6. -> 6 + | 7. -> 7 + | 8. -> 8 + | 9. -> 9 + | 10. | 10.1 -> 10 + | 10.2 -> 11 + | 10.3 -> 12 + | 11. -> 13 + | 11.1 -> 14 + | 11.2 -> 15 + | 11.3 -> 16 + | 11.4 -> 17 + | 11.5 -> 18 + | 11.6 -> 19 + | 11.7 -> 20 + | 11.8 -> 21 + | 11.9 -> 22 + | v when v >= 12.0 && float_of_int (int_of_float v) = v -> int_of_float v + 11 + | v -> failwith ("Invalid SWF version " ^ string_of_float v) + +let convert_header com flash_version (w,h,fps,bg) = let high = (max w h) * 20 in let rec loop b = if 1 lsl b > high then b else loop (b + 1) in let bits = loop 0 in { - h_version = Common.flash_version_tag com.flash_version; + h_version = flash_version_tag flash_version; h_size = { rect_nbits = bits + 1; left = 0; @@ -49,11 +70,11 @@ let convert_header com (w,h,fps,bg) = }; h_frame_count = 1; h_fps = to_float16 (if fps > 127.0 then 127.0 else fps); - h_compressed = not (Common.defined com Define.NoSwfCompress); + h_compressed = not (Gctx.defined com Define.NoSwfCompress); } , bg -let default_header com = - convert_header com (400,300,30.,0xFFFFFF) +let default_header com flash_version = + convert_header com flash_version (400,300,30.,0xFFFFFF) type dependency_kind = | DKInherit @@ -223,7 +244,7 @@ let detect_format data p = abort "Unknown file format" p let build_swf9 com file swc = - let boot_name = if swc <> None || Common.defined com Define.HaxeBoot then "haxe" else "boot_" ^ (String.sub (Digest.to_hex (Digest.string (Filename.basename file))) 0 4) in + let boot_name = if swc <> None || Gctx.defined com Define.HaxeBoot then "haxe" else "boot_" ^ (String.sub (Digest.to_hex (Digest.string (Filename.basename file))) 0 4) in let code = Genswf9.generate com boot_name in let code = (match swc with | Some cat -> @@ -255,8 +276,9 @@ let build_swf9 com file swc = classes := { f9_cid = Some !cid; f9_classname = s_type_path (Genswf9.resource_path name) } :: !classes; tag (TBinaryData (!cid,data)) :: acc ) com.resources [] in + let find_file f = (com.class_paths#find_file f).file in let load_file_data file p = - let file = try Common.find_file com file with Not_found -> file in + let file = try find_file file with Not_found -> file in if String.length file > 5 && String.sub file 0 5 = "data:" then String.sub file 5 (String.length file - 5) else @@ -435,12 +457,12 @@ let build_swf9 com file swc = let clips = [tag (TF9Classes (List.rev !classes))] in res @ bmp @ code @ clips -let merge com file priority (h1,tags1) (h2,tags2) = +let merge com flash_version file priority (h1,tags1) (h2,tags2) = (* prioritize header+bgcolor for first swf *) - let header = if priority then { h2 with h_version = max h2.h_version (Common.flash_version_tag com.flash_version) } else h1 in + let header = if priority then { h2 with h_version = max h2.h_version (flash_version_tag flash_version) } else h1 in let tags1 = if priority then List.filter (function { tdata = TSetBgColor _ } -> false | _ -> true) tags1 else tags1 in (* remove unused tags *) - let use_stage = priority && Common.defined com Define.FlashUseStage in + let use_stage = priority && Gctx.defined com Define.FlashUseStage in let classes = ref [] in let nframe = ref 0 in let tags2 = List.filter (fun t -> @@ -451,9 +473,9 @@ let merge com file priority (h1,tags1) (h2,tags2) = | TRemoveObject _ -> use_stage | TShowFrame -> incr nframe; use_stage | TFilesAttributes _ | TEnableDebugger2 _ | TScenes _ -> false - | TMetaData _ -> not (Common.defined com Define.SwfMetadata) + | TMetaData _ -> not (Gctx.defined com Define.SwfMetadata) | TSetBgColor _ -> priority - | TExport el when !nframe = 0 && com.flash_version >= 9. -> + | TExport el when !nframe = 0 && flash_version >= 9. -> let el = List.filter (fun e -> let path = parse_path e.exp_name in let b = List.exists (fun t -> t_path t = path) com.types in @@ -508,8 +530,8 @@ let merge com file priority (h1,tags1) (h2,tags2) = let tags = loop tags1 tags2 in header, tags -let generate swf_header com = - let swc = if Common.defined com Define.Swc then Some (ref "") else None in +let generate swf_header swf_libs flash_version com = + let swc = if Gctx.defined com Define.Swc then Some (ref "") else None in let file , codeclip = (try let f , c = ExtString.String.split com.file "@" in f, Some c with _ -> com.file , None) in (* list exports *) let exports = Hashtbl.create 0 in @@ -541,39 +563,40 @@ let generate swf_header com = ) el | _ -> () ) tags; - ) com.native_libs.swf_libs; + ) swf_libs; (* build haxe swf *) let tags = build_swf9 com file swc in - let header, bg = (match swf_header with None -> default_header com | Some h -> convert_header com h) in + let header, bg = (match swf_header with None -> default_header com flash_version | Some h -> convert_header com flash_version h) in let bg = tag (TSetBgColor { cr = bg lsr 16; cg = (bg lsr 8) land 0xFF; cb = bg land 0xFF }) in let scene = tag ~ext:true (TScenes ([(0,"Scene1")],[])) in let swf_debug_password = try - Digest.to_hex(Digest.string (Common.defined_value com Define.SwfDebugPassword)) + Digest.to_hex(Digest.string (Gctx.defined_value com Define.SwfDebugPassword)) with Not_found -> "" in - let debug = (if Common.defined com Define.Fdb then [tag (TEnableDebugger2 (0, swf_debug_password))] else []) in + let debug = (if Gctx.defined com Define.Fdb then [tag (TEnableDebugger2 (0, swf_debug_password))] else []) in let meta_data = try - let file = Common.defined_value com Define.SwfMetadata in - let file = try Common.find_file com file with Not_found -> file in + let file = Gctx.defined_value com Define.SwfMetadata in + let find_file f = (com.class_paths#find_file f).file in + let file = try find_file file with Not_found -> file in let data = try Std.input_file ~bin:true file with Sys_error _ -> failwith ("Metadata resource file not found : " ^ file) in [tag(TMetaData (data))] with Not_found -> [] in - let fattr = (if com.flash_version < 8. then [] else + let fattr = (if flash_version < 8. then [] else [tag (TFilesAttributes { - fa_network = Common.defined com Define.NetworkSandbox; + fa_network = Gctx.defined com Define.NetworkSandbox; fa_as3 = true; fa_metadata = meta_data <> []; - fa_gpu = com.flash_version > 9. && Common.defined com Define.SwfGpu; - fa_direct_blt = com.flash_version > 9. && Common.defined com Define.SwfDirectBlit; + fa_gpu = flash_version > 9. && Gctx.defined com Define.SwfGpu; + fa_direct_blt = flash_version > 9. && Gctx.defined com Define.SwfDirectBlit; })] ) in - let fattr = if Common.defined com Define.AdvancedTelemetry then fattr @ [tag (TUnknown (0x5D,"\x00\x00"))] else fattr in + let fattr = if Gctx.defined com Define.AdvancedTelemetry then fattr @ [tag (TUnknown (0x5D,"\x00\x00"))] else fattr in let swf_script_limits = try - let s = Common.defined_value com Define.SwfScriptTimeout in + let s = Gctx.defined_value com Define.SwfScriptTimeout in let i = try int_of_string s with _ -> abort "Argument to swf_script_timeout must be an integer" null_pos in [tag(TScriptLimits (256, if i < 0 then 0 else if i > 65535 then 65535 else i))] with Not_found -> @@ -583,12 +606,12 @@ let generate swf_header com = (* merge swf libraries *) let priority = ref (swf_header = None) in let swf = List.fold_left (fun swf swf_lib -> - let swf = merge com file !priority swf (SwfLoader.remove_classes toremove swf_lib#get_data swf_lib#list_modules) in + let swf = merge com flash_version file !priority swf (SwfLoader.remove_classes toremove swf_lib#get_data swf_lib#list_modules) in priority := false; swf - ) swf com.native_libs.swf_libs in + ) swf swf_libs in let swf = match swf with - | header,tags when Common.defined com Define.SwfPreloaderFrame -> + | header,tags when Gctx.defined com Define.SwfPreloaderFrame -> let rec loop l = match l with | ({tdata = TFilesAttributes _ | TUnknown (0x5D,"\x00\x00") | TMetaData _ | TSetBgColor _ | TEnableDebugger2 _ | TScriptLimits _} as t) :: l -> t :: loop l @@ -599,7 +622,7 @@ let generate swf_header com = | _ -> swf in (* write swf/swc *) let t = Timer.timer ["write";"swf"] in - let level = (try int_of_string (Common.defined_value com Define.SwfCompressLevel) with Not_found -> 9) in + let level = (try int_of_string (Gctx.defined_value com Define.SwfCompressLevel) with Not_found -> 9) in SwfParser.init Extc.input_zip (Extc.output_zip ~level); (match swc with | Some cat -> diff --git a/src/generators/genswf9.ml b/src/generators/genswf9.ml index 828a353b875..a414330b45b 100644 --- a/src/generators/genswf9.ml +++ b/src/generators/genswf9.ml @@ -19,11 +19,11 @@ open Extlib_leftovers open Globals open Ast +open Gctx open Type open Error open As3 open As3hl -open Common open FlashProps type read = Read @@ -81,7 +81,7 @@ type try_infos = { type context = { (* globals *) - com : Common.context; + com : Gctx.t; debugger : bool; swc : bool; boot : path; @@ -351,7 +351,7 @@ let property ctx fa t = | TInst ({ cl_path = [],"Array" },_) -> (match p with | "length" -> ident p, Some KInt, false (* UInt in the spec *) - | "map" | "filter" when Common.defined ctx.com Define.NoFlashOverride -> ident (p ^ "HX"), None, true + | "map" | "filter" when Gctx.defined ctx.com Define.NoFlashOverride -> ident (p ^ "HX"), None, true | "copy" | "insert" | "contains" | "remove" | "iterator" | "keyValueIterator" | "toString" | "map" | "filter" | "resize" -> ident p , None, true | _ -> as3 p, None, false); @@ -364,13 +364,13 @@ let property ctx fa t = | TInst ({ cl_path = [],"String" },_) -> (match p with | "length" (* Int in AS3/Haxe *) -> ident p, None, false - | "charCodeAt" when Common.defined ctx.com Define.NoFlashOverride -> ident (p ^ "HX"), None, true + | "charCodeAt" when Gctx.defined ctx.com Define.NoFlashOverride -> ident (p ^ "HX"), None, true | "charCodeAt" (* use Haxe version *) -> ident p, None, true | "cca" -> as3 "charCodeAt", None, false | _ -> as3 p, None, false); | TInst ({ cl_path = [],"Date" },_) -> (match p with - | "toString" when Common.defined ctx.com Define.NoFlashOverride -> ident (p ^ "HX"), None, true + | "toString" when Gctx.defined ctx.com Define.NoFlashOverride -> ident (p ^ "HX"), None, true | _ -> ident p, None, false) | TAnon a -> (match !(a.a_status) with @@ -2833,7 +2833,7 @@ let generate_resource ctx name = let generate com boot_name = let ctx = { com = com; - need_ctor_skip = Common.has_feature com "Type.createEmptyInstance"; + need_ctor_skip = Gctx.has_feature com "Type.createEmptyInstance"; handle_spread_args = (fun basic args t_result args_to_expr -> match List.rev args with | { eexpr = TUnop (Spread,Prefix,rest) } :: args_rev -> @@ -2869,12 +2869,12 @@ let generate com boot_name = | _ -> None ); - debug = com.Common.debug; + debug = com.Gctx.debug; cur_class = null_class; boot = ([],boot_name); - debugger = Common.defined com Define.Fdb; - swc = Common.defined com Define.Swc; - swf_protected = Common.defined com Define.SwfProtected; + debugger = Gctx.defined com Define.Fdb; + swc = Gctx.defined com Define.Swc; + swf_protected = Gctx.defined com Define.SwfProtected; code = DynArray.create(); locals = PMap.empty; infos = default_infos(); From b296662ca0632e317c35b8fdff0b362e0c4cb863 Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 14:27:36 +0100 Subject: [PATCH 09/13] php --- src/compiler/generate.ml | 4 +++- src/context/sourcemaps.ml | 4 ++-- src/generators/genphp7.ml | 18 ++++++++---------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index c398720bbc0..6b4a3eea76d 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -190,7 +190,9 @@ let generate ctx tctx ext actx = Genlua.generate (Common.to_gctx com) ),"lua" | Php -> - Genphp7.generate,"php" + (fun com -> + Genphp7.generate (Common.to_gctx com) + ),"php" | Cpp -> Gencpp.generate,"cpp" | Jvm -> diff --git a/src/context/sourcemaps.ml b/src/context/sourcemaps.ml index 3dd3e39cb47..761109bd108 100644 --- a/src/context/sourcemaps.ml +++ b/src/context/sourcemaps.ml @@ -1,6 +1,6 @@ open Extlib_leftovers open Globals -open Common +open Gctx (** Characters used for base64 VLQ encoding @@ -127,7 +127,7 @@ class sourcemap_writer (generated_file:string) = output_string channel ("\"sources\":[" ^ (String.concat "," (List.map (fun s -> "\"" ^ to_url s ^ "\"") sources)) ^ "],\n"); - if Common.defined com Define.SourceMapContent then begin + if Gctx.defined com Define.SourceMapContent then begin output_string channel ("\"sourcesContent\":[" ^ (String.concat "," (List.map (fun s -> try "\"" ^ StringHelper.s_escape (Std.input_file ~bin:true s) ^ "\"" with _ -> "null") sources)) ^ "],\n"); diff --git a/src/generators/genphp7.ml b/src/generators/genphp7.ml index 431d044aa58..036df53bbff 100644 --- a/src/generators/genphp7.ml +++ b/src/generators/genphp7.ml @@ -3,8 +3,8 @@ *) open Ast +open Gctx open Type -open Common open Meta open Globals open Sourcemaps @@ -72,7 +72,7 @@ type used_type = { } type php_generator_context = { - pgc_common : Common.context; + pgc_common : Gctx.t; (** Do not add comments with Haxe positions before each line of generated php code *) pgc_skip_line_directives : bool; (** The value of `-D php-prefix=value` split by dots *) @@ -2011,8 +2011,6 @@ class code_writer (ctx:php_generator_context) hx_type_path php_name = @see http://old.haxe.org/doc/advanced/magic#php-magic *) method write_expr_magic name args = - let msg = "untyped " ^ name ^ " is deprecated. Use php.Syntax instead." in - DeprecationCheck.warn_deprecation (DeprecationCheck.create_context ctx.pgc_common) msg self#pos; let error = ("Invalid arguments for " ^ name ^ " magic call") in match args with | [] -> fail ~msg:error self#pos __LOC__ @@ -3944,7 +3942,7 @@ class generator (ctx:php_generator_context) = and name = builder#get_name in let filename = (create_dir_recursive (build_dir :: namespace)) ^ "/" ^ name ^ ".php" in let channel = open_out filename in - if Common.defined ctx.pgc_common Define.SourceMap then + if Gctx.defined ctx.pgc_common Define.SourceMap then builder#set_sourcemap_generator (new sourcemap_builder filename); output_string channel builder#get_contents; close_out channel; @@ -3993,7 +3991,7 @@ class generator (ctx:php_generator_context) = match self#get_entry_point with | None -> () | Some (uses, entry_point) -> - let filename = Common.defined_value_safe ~default:"index.php" ctx.pgc_common Define.PhpFront in + let filename = Gctx.defined_value_safe ~default:"index.php" ctx.pgc_common Define.PhpFront in let front_dirs = split_file_path (Filename.dirname filename) in if front_dirs <> [] then ignore(create_dir_recursive (root_dir :: front_dirs)); @@ -4032,7 +4030,7 @@ class generator (ctx:php_generator_context) = Returns path from `index.php` to directory which will contain all generated classes *) method private get_lib_path : string list = - let path = Common.defined_value_safe ~default:"lib" ctx.pgc_common Define.PhpLib in + let path = Gctx.defined_value_safe ~default:"lib" ctx.pgc_common Define.PhpLib in split_file_path path (** Returns PHP code for entry point @@ -4069,12 +4067,12 @@ let get_boot com : tclass = (** Entry point to Genphp7 *) -let generate (com:context) = +let generate (com:Gctx.t) = let ctx = { pgc_common = com; - pgc_skip_line_directives = Common.defined com Define.RealPosition; - pgc_prefix = Str.split (Str.regexp "\\.") (Common.defined_value_safe com Define.PhpPrefix); + pgc_skip_line_directives = Gctx.defined com Define.RealPosition; + pgc_prefix = Str.split (Str.regexp "\\.") (Gctx.defined_value_safe com Define.PhpPrefix); pgc_boot = get_boot com; pgc_namespaces_types_cache = Hashtbl.create 512; pgc_anons = Hashtbl.create 0; From 25e3204ee432239c11b42b1b84720834daa35c7a Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 15:14:44 +0100 Subject: [PATCH 10/13] cpp --- src/compiler/generate.ml | 4 ++- src/generators/cpp/cppContext.ml | 10 ++++---- src/generators/cpp/cppRetyper.ml | 3 +-- src/generators/cpp/cppSourceWriter.ml | 10 ++++---- src/generators/cpp/cppStrings.ml | 2 +- src/generators/cpp/gen/cppCppia.ml | 7 +++--- src/generators/cpp/gen/cppGen.ml | 6 ++--- src/generators/cpp/gen/cppGenClassHeader.ml | 11 ++++---- .../cpp/gen/cppGenClassImplementation.ml | 7 +++--- src/generators/cpp/gen/cppGenEnum.ml | 5 ++-- src/generators/gctx.ml | 3 +++ src/generators/gencpp.ml | 25 ++++++++++--------- 12 files changed, 47 insertions(+), 46 deletions(-) diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index 6b4a3eea76d..e6d7172a508 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -194,7 +194,9 @@ let generate ctx tctx ext actx = Genphp7.generate (Common.to_gctx com) ),"php" | Cpp -> - Gencpp.generate,"cpp" + (fun com -> + Gencpp.generate (Common.to_gctx com) + ),"cpp" | Jvm -> (fun com -> Genjvm.generate actx.jvm_flag (Common.to_gctx com) diff --git a/src/generators/cpp/cppContext.ml b/src/generators/cpp/cppContext.ml index 6a45ca0895e..958f26f8467 100644 --- a/src/generators/cpp/cppContext.ml +++ b/src/generators/cpp/cppContext.ml @@ -1,8 +1,8 @@ open Extlib_leftovers open Ast +open Gctx open Type open Error -open Common open Globals open CppAstTools @@ -18,7 +18,7 @@ open CppAstTools normal = 1 *) type context = { - ctx_common : Common.context; + ctx_common : Gctx.t; mutable ctx_debug_level : int; (* cached as required *) mutable ctx_file_info : (string, string) PMap.t ref; @@ -39,7 +39,7 @@ let new_context common_ctx debug file_info member_types = let null_file = new CppSourceWriter.source_writer common_ctx ignore ignore (fun () -> ()) in - let has_def def = Common.defined_value_safe common_ctx def <> "" in + let has_def def = Gctx.defined_value_safe common_ctx def <> "" in let result = { ctx_common = common_ctx; @@ -94,8 +94,8 @@ let hash_keys hash = !key_list let is_gc_element ctx member_type = - Common.defined ctx.ctx_common Define.HxcppGcGenerational && (is_object_element member_type) + Gctx.defined ctx.ctx_common Define.HxcppGcGenerational && (is_object_element member_type) -let strip_file ctx file = match Common.defined ctx Common.Define.AbsolutePath with +let strip_file ctx file = match Gctx.defined ctx Define.AbsolutePath with | true -> Path.get_full_path file | false -> ctx.class_paths#relative_path file \ No newline at end of file diff --git a/src/generators/cpp/cppRetyper.ml b/src/generators/cpp/cppRetyper.ml index 8aea5442f50..b04927ed9b2 100644 --- a/src/generators/cpp/cppRetyper.ml +++ b/src/generators/cpp/cppRetyper.ml @@ -2,7 +2,6 @@ open Extlib_leftovers open Ast open Type open Error -open Common open Globals open CppExprUtils open CppTypeUtils @@ -195,7 +194,7 @@ let expression ctx request_type function_args function_type expression_tree forI let file_id = ctx.ctx_file_id in let function_return_type = ref (cpp_type_of function_type) in let loop_stack = ref [] in - let forCppia = Common.defined ctx.ctx_common Define.Cppia in + let forCppia = Gctx.defined ctx.ctx_common Define.Cppia in let alloc_file_id () = incr file_id; !file_id diff --git a/src/generators/cpp/cppSourceWriter.ml b/src/generators/cpp/cppSourceWriter.ml index 33109d69cb0..1371cf31a89 100644 --- a/src/generators/cpp/cppSourceWriter.ml +++ b/src/generators/cpp/cppSourceWriter.ml @@ -1,8 +1,8 @@ open Extlib_leftovers open Ast +open Gctx open Type open Error -open Common open Globals open CppStrings open CppAstTools @@ -16,7 +16,7 @@ open CppTypeUtils let get_include_prefix common_ctx with_slash = try - Common.defined_value common_ctx Define.IncludePrefix ^ if with_slash then "/" else "" + Gctx.defined_value common_ctx Define.IncludePrefix ^ if with_slash then "/" else "" with Not_found -> "" let should_prefix_include = function @@ -35,10 +35,10 @@ let guarded_include file = let source_file_extension common_ctx = (* no need to -D file_extension if -D objc is defined *) - if Common.defined common_ctx Define.Objc then ".mm" + if Gctx.defined common_ctx Define.Objc then ".mm" else try - "." ^ Common.defined_value common_ctx Define.FileExtension + "." ^ Gctx.defined_value common_ctx Define.FileExtension with Not_found -> ".cpp" class source_writer common_ctx write_header_func write_func close_func = @@ -179,7 +179,7 @@ let new_header_file common_ctx base_dir = let new_placed_cpp_file common_ctx class_path = let base_dir = common_ctx.file in - if (Common.defined common_ctx Define.Vcproj ) then begin + if (Gctx.defined common_ctx Define.Vcproj ) then begin Path.mkdir_recursive base_dir ("src"::[]); cached_source_writer common_ctx ( base_dir ^ "/src/" ^ ( String.concat "-" (fst class_path) ) ^ "-" ^ diff --git a/src/generators/cpp/cppStrings.ml b/src/generators/cpp/cppStrings.ml index 62e5e433b89..99a8d76ef54 100644 --- a/src/generators/cpp/cppStrings.ml +++ b/src/generators/cpp/cppStrings.ml @@ -68,7 +68,7 @@ let strq ctx s = else "(" ^ split s "" ^ ")" in - if Common.defined ctx Define.HxcppSmartStings && has_utf8_chars s then ( + if Gctx.defined ctx Define.HxcppSmartStings && has_utf8_chars s then ( let b = Buffer.create 0 in let add ichar = diff --git a/src/generators/cpp/gen/cppCppia.ml b/src/generators/cpp/gen/cppCppia.ml index 2d9259d88d1..08eb43d1108 100644 --- a/src/generators/cpp/gen/cppCppia.ml +++ b/src/generators/cpp/gen/cppCppia.ml @@ -2,7 +2,6 @@ open Extlib_leftovers open Ast open Type open Error -open Common open Globals open CppExprUtils open CppTypeUtils @@ -499,7 +498,7 @@ class script_writer ctx filename asciiOut = val debug = asciiOut val doComment = - asciiOut && Common.defined ctx.ctx_common Define.AnnotateSource + asciiOut && Gctx.defined ctx.ctx_common Define.AnnotateSource val indent_str = if asciiOut then "\t" else "" val mutable indent = "" @@ -511,7 +510,7 @@ class script_writer ctx filename asciiOut = val identTable = Hashtbl.create 0 val fileTable = Hashtbl.create 0 val identBuffer = Buffer.create 0 - val cppiaAst = not (Common.defined ctx.ctx_common Define.NoCppiaAst) + val cppiaAst = not (Gctx.defined ctx.ctx_common Define.NoCppiaAst) method stringId name = try Hashtbl.find identTable name @@ -1800,7 +1799,7 @@ let generate_script_class common_ctx script class_def = if Meta.has Meta.NativeProperty class_def.cl_meta || Meta.has Meta.NativeProperty field.cf_meta - || Common.defined common_ctx Define.ForceNativeProperty + || Gctx.defined common_ctx Define.ForceNativeProperty then IaAccessCallNative else IaAccessCall | AccInline -> IaAccessNormal diff --git a/src/generators/cpp/gen/cppGen.ml b/src/generators/cpp/gen/cppGen.ml index dfe0faecca0..f5c9061c6cc 100644 --- a/src/generators/cpp/gen/cppGen.ml +++ b/src/generators/cpp/gen/cppGen.ml @@ -1,7 +1,7 @@ open Ast +open Gctx open Type open Error -open Common open Globals open CppStrings open CppExprUtils @@ -1752,7 +1752,7 @@ let generate_boot ctx boot_enums boot_classes nonboot_classes init_classes = (fun class_path -> boot_file#add_include class_path) (boot_enums @ boot_classes @ nonboot_classes); - let newScriptable = Common.defined common_ctx Define.Scriptable in + let newScriptable = Gctx.defined common_ctx Define.Scriptable in if newScriptable then ( output_boot "#include \n"; let funcs = @@ -1836,7 +1836,7 @@ let generate_files common_ctx file_info = output_files (const_char_star (Path.get_full_path - (try Common.find_file common_ctx file with Not_found -> file)) + (try Gctx.find_file common_ctx file with Not_found -> file)) ^ ",\n")) (List.sort String.compare (pmap_keys !file_info)); output_files "#endif\n"; diff --git a/src/generators/cpp/gen/cppGenClassHeader.ml b/src/generators/cpp/gen/cppGenClassHeader.ml index 8a12ebcc8fc..4a813471de7 100644 --- a/src/generators/cpp/gen/cppGenClassHeader.ml +++ b/src/generators/cpp/gen/cppGenClassHeader.ml @@ -1,7 +1,6 @@ open Ast open Type open Error -open Common open Globals open CppStrings open CppExprUtils @@ -30,7 +29,7 @@ let gen_member_def ctx class_def is_static is_interface field = output (gen_args args); output (if not is_static then ")=0;\n" else ");\n"); if reflective class_def field then - if Common.defined ctx.ctx_common Define.DynamicInterfaceClosures + if Gctx.defined ctx.ctx_common Define.DynamicInterfaceClosures then output ("\t\tinline ::Dynamic " ^ remap_name @@ -96,7 +95,7 @@ let gen_member_def ctx class_def is_static is_interface field = let return_type = type_to_string function_def.tf_type in (if (not is_static) && not nonVirtual then let scriptable = - Common.defined ctx.ctx_common Define.Scriptable + Gctx.defined ctx.ctx_common Define.Scriptable in if (not (is_internal_member field.cf_name)) && not scriptable then let key = @@ -202,7 +201,7 @@ let generate baseCtx class_def = let nativeGen = Meta.has Meta.NativeGen class_def.cl_meta in let smart_class_name = snd class_path in let scriptable = - Common.defined common_ctx Define.Scriptable && not class_def.cl_private + Gctx.defined common_ctx Define.Scriptable && not class_def.cl_private in let class_name = class_name class_def in let ptr_name = class_pointer class_def in @@ -220,7 +219,7 @@ let generate baseCtx class_def = let debug = if Meta.has Meta.NoDebug class_def.cl_meta - || Common.defined baseCtx.ctx_common Define.NoDebug + || Gctx.defined baseCtx.ctx_common Define.NoDebug then 0 else 1 in @@ -299,7 +298,7 @@ let generate baseCtx class_def = output_h "\n\n"; output_h (get_class_code class_def Meta.HeaderNamespaceCode); - let extern_class = Common.defined common_ctx Define.DllExport in + let extern_class = Gctx.defined common_ctx Define.DllExport in let attribs = "HXCPP_" ^ (if extern_class then "EXTERN_" else "") ^ "CLASS_ATTRIBUTES" in diff --git a/src/generators/cpp/gen/cppGenClassImplementation.ml b/src/generators/cpp/gen/cppGenClassImplementation.ml index 009b237f43e..5ee9861bdc4 100644 --- a/src/generators/cpp/gen/cppGenClassImplementation.ml +++ b/src/generators/cpp/gen/cppGenClassImplementation.ml @@ -1,7 +1,6 @@ open Ast open Type open Error -open Common open Globals open CppStrings open CppExprUtils @@ -301,7 +300,7 @@ let generate baseCtx class_def = let output_cpp = cpp_file#write in let strq = strq ctx.ctx_common in let scriptable = - Common.defined common_ctx Define.Scriptable && not class_def.cl_private + Gctx.defined common_ctx Define.Scriptable && not class_def.cl_private in let class_super_name = @@ -690,7 +689,7 @@ let generate baseCtx class_def = if Meta.has Meta.NativeProperty class_def.cl_meta || Meta.has Meta.NativeProperty field.cf_meta - || Common.defined common_ctx Define.ForceNativeProperty + || Gctx.defined common_ctx Define.ForceNativeProperty then "inCallProp != ::hx::paccNever" else "inCallProp == ::hx::paccAlways" in @@ -1114,7 +1113,7 @@ let generate baseCtx class_def = if return_type <> "void" then output_cpp "return null();"; output_cpp "}\n"; let dynamic_interface_closures = - Common.defined baseCtx.ctx_common Define.DynamicInterfaceClosures + Gctx.defined baseCtx.ctx_common Define.DynamicInterfaceClosures in if has_class_flag class_def CInterface && not dynamic_interface_closures then diff --git a/src/generators/cpp/gen/cppGenEnum.ml b/src/generators/cpp/gen/cppGenEnum.ml index 287ab5d5558..ae00e32708f 100644 --- a/src/generators/cpp/gen/cppGenEnum.ml +++ b/src/generators/cpp/gen/cppGenEnum.ml @@ -1,7 +1,6 @@ open Ast open Type open Error -open Common open Globals open CppStrings open CppExprUtils @@ -20,7 +19,7 @@ let generate baseCtx enum_def = let remap_class_name = ("::" ^ (join_class_path_remap class_path "::") ) in let cpp_file = new_placed_cpp_file common_ctx class_path in let output_cpp = (cpp_file#write) in - let debug = if (Meta.has Meta.NoDebug enum_def.e_meta) || ( Common.defined common_ctx Define.NoDebug) then 0 else 1 in + let debug = if (Meta.has Meta.NoDebug enum_def.e_meta) || ( Gctx.defined common_ctx Define.NoDebug) then 0 else 1 in let ctx = file_context baseCtx cpp_file debug false in let strq = strq ctx.ctx_common in @@ -209,4 +208,4 @@ let generate baseCtx enum_def = end_namespace output_h class_path; end_header_file output_h def_string; - h_file#close + h_file#close diff --git a/src/generators/gctx.ml b/src/generators/gctx.ml index 04c17b55b32..0598e6d503d 100644 --- a/src/generators/gctx.ml +++ b/src/generators/gctx.ml @@ -49,6 +49,9 @@ let defined_value_safe ?default com v = let raw_defined gctx v = Define.raw_defined gctx.defines v +let find_file ctx f = + (ctx.class_paths#find_file f).file + let add_feature gctx f = Hashtbl.replace gctx.features f true diff --git a/src/generators/gencpp.ml b/src/generators/gencpp.ml index 3c06e600b17..b3cd74b659e 100644 --- a/src/generators/gencpp.ml +++ b/src/generators/gencpp.ml @@ -17,9 +17,9 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *) open Ast +open Gctx open Type open Error -open Common open Globals open CppStrings open CppExprUtils @@ -127,7 +127,7 @@ let write_build_data common_ctx filename classes main_deps boot_deps build_extra in output_string buildfile "\n"; - let api_string = (Common.defined_value common_ctx Define.HxcppApiLevel) in + let api_string = (Gctx.defined_value common_ctx Define.HxcppApiLevel) in output_string buildfile ("\n"); output_string buildfile "\n"; output_string buildfile "\n"; @@ -160,7 +160,7 @@ let write_build_data common_ctx filename classes main_deps boot_deps build_extra output_string buildfile ("\n"); output_string buildfile "\n"; output_string buildfile build_extra; - if (Common.defined common_ctx Define.HxcppSmartStings) then + if (Gctx.defined common_ctx Define.HxcppSmartStings) then output_string buildfile ("\n"); output_string buildfile "\n"; close_out buildfile @@ -225,13 +225,13 @@ let generate_source ctx = let extern_src = ref [] in let jobs = ref [] in let build_xml = ref "" in - let scriptable = (Common.defined common_ctx Define.Scriptable) in + let scriptable = (Gctx.defined common_ctx Define.Scriptable) in let existingIds = Hashtbl.create 0 in List.iter (fun object_def -> (* check if any @:objc class is referenced while '-D objc' is not defined This will guard all code changes to this flag *) - (if not (Common.defined common_ctx Define.Objc) then match object_def with + (if not (Gctx.defined common_ctx Define.Objc) then match object_def with | TClassDecl class_def when Meta.has Meta.Objc class_def.cl_meta -> abort "In order to compile '@:objc' classes, please define '-D objc'" class_def.cl_pos | _ -> ()); @@ -320,10 +320,10 @@ let generate_source ctx = write_resources common_ctx; (* Output class info if requested *) - if (scriptable || (Common.defined common_ctx Define.DllExport) ) then begin + if (scriptable || (Gctx.defined common_ctx Define.DllExport) ) then begin let filename = try - let value = Common.defined_value common_ctx Define.DllExport in + let value = Gctx.defined_value common_ctx Define.DllExport in if value="1" then raise Not_found; value with Not_found -> "export_classes.info" @@ -357,7 +357,7 @@ let generate_source ctx = (* Output file info too *) List.iter ( fun file -> - let full_path = Path.get_full_path (try Common.find_file common_ctx file with Not_found -> file) in + let full_path = Path.get_full_path (try Gctx.find_file common_ctx file with Not_found -> file) in if file <> "?" then out ("file " ^ (escape file) ^ " " ^ (escape full_path) ^"\n") ) ( List.sort String.compare ( pmap_keys !(ctx.ctx_file_info) ) ); @@ -371,7 +371,7 @@ let generate_source ctx = write_build_data common_ctx (common_ctx.file ^ "/Build.xml") !exe_classes !main_deps (!boot_enums@ !boot_classes) !build_xml !extern_src output_name; write_build_options common_ctx (common_ctx.file ^ "/Options.txt") common_ctx.defines.Define.values; - if ( not (Common.defined common_ctx Define.NoCompilation) ) then begin + if ( not (Gctx.defined common_ctx Define.NoCompilation) ) then begin let t = Timer.timer ["generate";"cpp";"native compilation"] in let old_dir = Sys.getcwd() in Sys.chdir common_ctx.file; @@ -385,15 +385,16 @@ let generate_source ctx = let path = path#path in cmd := !cmd @ [Printf.sprintf "-I%s" (escape_command path)] ); - common_ctx.print ("haxelib " ^ (String.concat " " !cmd) ^ "\n"); + (* GCTX_TODO *) + (* common_ctx.print ("haxelib " ^ (String.concat " " !cmd) ^ "\n"); *) if common_ctx.run_command_args "haxelib" !cmd <> 0 then failwith "Build failed"; Sys.chdir old_dir; t() end let generate common_ctx = - let debug_level = if (Common.defined common_ctx Define.NoDebug) then 0 else 1 in - if (Common.defined common_ctx Define.Cppia) then begin + let debug_level = if (Gctx.defined common_ctx Define.NoDebug) then 0 else 1 in + if (Gctx.defined common_ctx Define.Cppia) then begin let ctx = new_context common_ctx debug_level (ref PMap.empty) (Hashtbl.create 0) in CppCppia.generate_cppia ctx end else begin From d63bc0baa02b1a188f3e58a2f1a6c48bc2ba958c Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 15:17:04 +0100 Subject: [PATCH 11/13] cleanup --- src/compiler/generate.ml | 38 ++++++++++---------------------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/src/compiler/generate.ml b/src/compiler/generate.ml index e6d7172a508..e40fee92022 100644 --- a/src/compiler/generate.ml +++ b/src/compiler/generate.ml @@ -174,41 +174,23 @@ let generate ctx tctx ext actx = with Not_found -> None in - (fun com -> - Genswf.generate header com.Common.native_libs.swf_libs com.Common.flash_version (Common.to_gctx com) - ),"swf" + Genswf.generate header com.Common.native_libs.swf_libs com.Common.flash_version,"swf" | Neko -> - (fun com -> - Genneko.generate com.neko_lib_paths (Common.to_gctx com) - ),"neko" + Genneko.generate com.neko_lib_paths,"neko" | Js -> - (fun com -> - Genjs.generate com.js_gen (Common.to_gctx com) - ),"js" + Genjs.generate com.js_gen,"js" | Lua -> - (fun com -> - Genlua.generate (Common.to_gctx com) - ),"lua" + Genlua.generate,"lua" | Php -> - (fun com -> - Genphp7.generate (Common.to_gctx com) - ),"php" + Genphp7.generate,"php" | Cpp -> - (fun com -> - Gencpp.generate (Common.to_gctx com) - ),"cpp" + Gencpp.generate,"cpp" | Jvm -> - (fun com -> - Genjvm.generate actx.jvm_flag (Common.to_gctx com) - ),"jvm" + Genjvm.generate actx.jvm_flag,"jvm" | Python -> - (fun com -> - Genpy.generate (Common.to_gctx com) - ),"python" + Genpy.generate,"python" | Hl -> - (fun com -> - Genhl.generate (Common.to_gctx com) - ),"hl" + Genhl.generate,"hl" | Eval -> (fun _ -> MacroContext.interpret tctx),"eval" | Cross @@ -219,7 +201,7 @@ let generate ctx tctx ext actx = else begin Common.log com ("Generating " ^ name ^ ": " ^ com.file); let t = Timer.timer ["generate";name] in - generate com; + generate (Common.to_gctx com); t() end end From a930e9d01661e3b99f2783f47f289cced764b90e Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 15:18:57 +0100 Subject: [PATCH 12/13] more cleanup --- src/generators/cpp/cppAst.ml | 1 - src/generators/cpp/cppAstTools.ml | 5 ++--- src/generators/cpp/cppExprUtils.ml | 1 - src/generators/cpp/cppTypeUtils.ml | 9 ++++----- src/generators/cpp/gen/cppReferences.ml | 1 - 5 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/generators/cpp/cppAst.ml b/src/generators/cpp/cppAst.ml index 9b40716bf34..96707878ff3 100644 --- a/src/generators/cpp/cppAst.ml +++ b/src/generators/cpp/cppAst.ml @@ -2,7 +2,6 @@ open Extlib_leftovers open Ast open Type open Error -open Common open Globals type tcpp = diff --git a/src/generators/cpp/cppAstTools.ml b/src/generators/cpp/cppAstTools.ml index ecbdb5c3b70..6e0882f38d0 100644 --- a/src/generators/cpp/cppAstTools.ml +++ b/src/generators/cpp/cppAstTools.ml @@ -2,7 +2,6 @@ open Extlib_leftovers open Ast open Type open Error -open Common open Globals open CppAst open CppTypeUtils @@ -575,7 +574,7 @@ and type_string_remap remap haxe_type = and type_string haxe_type = type_string_suff "" haxe_type true - + and cpp_enum_path_of enum = let globalNamespace = match get_meta_string enum.e_meta Meta.Native with @@ -614,7 +613,7 @@ and gen_interface_arg_type_name name opt typ = and gen_tfun_interface_arg_list args = String.concat "," (List.map (fun (name,opt,typ) -> gen_interface_arg_type_name name opt typ) args) - + and cant_be_null haxe_type = is_numeric haxe_type || (type_has_meta_key Meta.NotNull haxe_type ) diff --git a/src/generators/cpp/cppExprUtils.ml b/src/generators/cpp/cppExprUtils.ml index 2bb10e72be6..4ee8a3f2f3e 100644 --- a/src/generators/cpp/cppExprUtils.ml +++ b/src/generators/cpp/cppExprUtils.ml @@ -2,7 +2,6 @@ open Extlib_leftovers open Ast open Type open Error -open Common open Globals let rec remove_parens expression = diff --git a/src/generators/cpp/cppTypeUtils.ml b/src/generators/cpp/cppTypeUtils.ml index ea1c3bff140..d11fcb6712e 100644 --- a/src/generators/cpp/cppTypeUtils.ml +++ b/src/generators/cpp/cppTypeUtils.ml @@ -5,7 +5,6 @@ open Extlib_leftovers open Ast open Type open Error -open Common open Globals let follow = Abstract.follow_with_abstracts @@ -15,18 +14,18 @@ let is_native_gen_class class_def = match class_def.cl_kind with | KAbstractImpl abstract_def -> Meta.has Meta.NativeGen abstract_def.a_meta | _ -> false - + let is_native_gen_module = function | TClassDecl class_def -> is_native_gen_class class_def | _ -> false - + let is_extern_class class_def = has_class_flag class_def CExtern || Meta.has Meta.Extern class_def.cl_meta || match class_def.cl_kind with | KAbstractImpl abstract_def -> Meta.has Meta.Extern abstract_def.a_meta | _ -> false - + let is_extern_enum enum_def = has_enum_flag enum_def EnExtern || Meta.has Meta.Extern enum_def.e_meta @@ -134,7 +133,7 @@ let is_numeric t = -> true | _ -> false - + let is_cpp_function_instance t = match follow t with | TInst ({ cl_path = (["cpp"], "Function") }, _) -> true diff --git a/src/generators/cpp/gen/cppReferences.ml b/src/generators/cpp/gen/cppReferences.ml index 703b9458f60..15e39fe5989 100644 --- a/src/generators/cpp/gen/cppReferences.ml +++ b/src/generators/cpp/gen/cppReferences.ml @@ -1,7 +1,6 @@ open Ast open Type open Error -open Common open Globals open CppStrings open CppExprUtils From 2d0ff444770a3c4fa7441f3c7ba31e5dd19f9c12 Mon Sep 17 00:00:00 2001 From: Simon Krajewski Date: Fri, 22 Nov 2024 17:04:24 +0100 Subject: [PATCH 13/13] final cleanup maybe --- src/context/common.ml | 3 ++- src/generators/cpp/cppSourceWriter.ml | 2 +- src/generators/gctx.ml | 9 +++++++++ src/generators/gctx_todo.ml | 9 --------- src/generators/gencpp.ml | 3 +-- src/generators/genjs.ml | 6 +++--- src/generators/genlua.ml | 2 +- src/generators/genneko.ml | 3 +-- src/generators/genphp7.ml | 2 +- src/generators/genpy.ml | 2 +- src/generators/genswf.ml | 6 ++---- src/generators/hl2c.ml | 2 +- src/typing/macroContext.ml | 2 +- 13 files changed, 24 insertions(+), 27 deletions(-) delete mode 100644 src/generators/gctx_todo.ml diff --git a/src/context/common.ml b/src/context/common.ml index 45ddec71f30..eaf0048645e 100644 --- a/src/context/common.ml +++ b/src/context/common.ml @@ -437,6 +437,7 @@ let to_gctx com = { run_command_args = com.run_command_args; warning = com.warning; error = com.error; + print = com.print; debug = com.debug; file = com.file; version = com.version; @@ -604,7 +605,7 @@ let get_config com = (* impossible to reach. see update_platform_config *) raise Exit | Js -> - let es6 = Gctx_todo.get_es_version com.defines >= 6 in + let es6 = Gctx.get_es_version com.defines >= 6 in { default_config with pf_static = false; diff --git a/src/generators/cpp/cppSourceWriter.ml b/src/generators/cpp/cppSourceWriter.ml index 1371cf31a89..874d63782a5 100644 --- a/src/generators/cpp/cppSourceWriter.ml +++ b/src/generators/cpp/cppSourceWriter.ml @@ -166,7 +166,7 @@ let new_source_file common_ctx base_dir sub_dir extension class_path = let file = cached_source_writer common_ctx (full_dir ^ "/" ^ snd class_path ^ extension) in - Gctx_todo.map_source_header common_ctx.defines (fun s -> + Gctx.map_source_header common_ctx.defines (fun s -> file#write_h (Printf.sprintf "// %s\n" s)); file diff --git a/src/generators/gctx.ml b/src/generators/gctx.ml index 0598e6d503d..2785bcf1cef 100644 --- a/src/generators/gctx.ml +++ b/src/generators/gctx.ml @@ -18,6 +18,7 @@ type t = { run_command_args : string -> string list -> int; warning : warning_function; error : error_function; + print : string -> unit; basic : basic_types; debug : bool; file : string; @@ -108,3 +109,11 @@ let get_entry_point gctx = let e = Option.get gctx.main.main_expr in (* must be present at this point *) (snd path, c, e) ) gctx.main.main_class + +let get_es_version defines = + try int_of_string (Define.defined_value defines Define.JsEs) with _ -> 0 + +let map_source_header defines f = + match Define.defined_value_safe defines Define.SourceHeader with + | "" -> () + | s -> f s \ No newline at end of file diff --git a/src/generators/gctx_todo.ml b/src/generators/gctx_todo.ml deleted file mode 100644 index be907f03cd0..00000000000 --- a/src/generators/gctx_todo.ml +++ /dev/null @@ -1,9 +0,0 @@ -open Define - -let get_es_version defines = - try int_of_string (Define.defined_value defines Define.JsEs) with _ -> 0 - -let map_source_header defines f = - match Define.defined_value_safe defines Define.SourceHeader with - | "" -> () - | s -> f s \ No newline at end of file diff --git a/src/generators/gencpp.ml b/src/generators/gencpp.ml index b3cd74b659e..1999ca983bc 100644 --- a/src/generators/gencpp.ml +++ b/src/generators/gencpp.ml @@ -385,8 +385,7 @@ let generate_source ctx = let path = path#path in cmd := !cmd @ [Printf.sprintf "-I%s" (escape_command path)] ); - (* GCTX_TODO *) - (* common_ctx.print ("haxelib " ^ (String.concat " " !cmd) ^ "\n"); *) + common_ctx.print ("haxelib " ^ (String.concat " " !cmd) ^ "\n"); if common_ctx.run_command_args "haxelib" !cmd <> 0 then failwith "Build failed"; Sys.chdir old_dir; t() diff --git a/src/generators/genjs.ml b/src/generators/genjs.ml index 7aca7a50f1f..ce8c98dbd0a 100644 --- a/src/generators/genjs.ml +++ b/src/generators/genjs.ml @@ -89,7 +89,7 @@ let es5kwds = [ let setup_kwds com = Hashtbl.reset kwds; - let es_version = Gctx_todo.get_es_version com.defines in + let es_version = Gctx.get_es_version com.defines in let lst = if es_version >= 5 then es5kwds else es3kwds in List.iter (fun s -> Hashtbl.add kwds s ()) lst @@ -1697,13 +1697,13 @@ let generate js_gen com = | Some g -> g() | None -> - let es_version = Gctx_todo.get_es_version com.defines in + let es_version = Gctx.get_es_version com.defines in if es_version >= 6 then ES6Ctors.rewrite_ctors com; let ctx = alloc_ctx com es_version in - Gctx_todo.map_source_header com.defines (fun s -> print ctx "// %s\n" s); + Gctx.map_source_header com.defines (fun s -> print ctx "// %s\n" s); if has_feature ctx "Class" || has_feature ctx "Type.getClassName" then add_feature ctx "js.Boot.isClass"; if has_feature ctx "Enum" || has_feature ctx "Type.getEnumName" then add_feature ctx "js.Boot.isEnum"; diff --git a/src/generators/genlua.ml b/src/generators/genlua.ml index 9107e10bf41..b0bb638f4fd 100644 --- a/src/generators/genlua.ml +++ b/src/generators/genlua.ml @@ -2009,7 +2009,7 @@ let transform_multireturn ctx = function let generate com = let ctx = alloc_ctx com in - Gctx_todo.map_source_header com.defines (fun s -> print ctx "-- %s\n" s); + Gctx.map_source_header com.defines (fun s -> print ctx "-- %s\n" s); if has_feature ctx "Class" || has_feature ctx "Type.getClassName" then add_feature ctx "lua.Boot.isClass"; if has_feature ctx "Enum" || has_feature ctx "Type.getEnumName" then add_feature ctx "lua.Boot.isEnum"; diff --git a/src/generators/genneko.ml b/src/generators/genneko.ml index 15295a513da..13b7cd0cabe 100644 --- a/src/generators/genneko.ml +++ b/src/generators/genneko.ml @@ -784,7 +784,6 @@ let generate neko_lib_paths com = let e = (EBlock ((header()) @ libs :: el @ emain), null_pos) in let source = Gctx.defined com Define.NekoSource in let use_nekoc = Gctx.defined com Define.UseNekoc in - let find_file f = (com.class_paths#find_file f).file in if not use_nekoc then begin try Path.mkdir_from_path com.file; @@ -792,7 +791,7 @@ let generate neko_lib_paths com = Nbytecode.write ch (Ncompile.compile ctx.version e); IO.close_out ch; with Ncompile.Error (msg,pos) -> - let pfile = find_file pos.psource in + let pfile = Gctx.find_file com pos.psource in let rec loop p = let pp = { pfile = pfile; pmin = p; pmax = p; } in if Lexer.get_error_line pp >= pos.pline then diff --git a/src/generators/genphp7.ml b/src/generators/genphp7.ml index 036df53bbff..2cd92e8f6b0 100644 --- a/src/generators/genphp7.ml +++ b/src/generators/genphp7.ml @@ -3043,7 +3043,7 @@ class virtual type_builder ctx (wrapper:type_wrapper) = writer#indent 0; writer#write_line " writer#write_line (" * " ^ s)); + Gctx.map_source_header ctx.pgc_common.defines (fun s -> writer#write_line (" * " ^ s)); if ctx.pgc_common.debug then writer#write_line (" * Haxe source file: " ^ self#get_source_file); writer#write_line " */"; writer#write "\n"; diff --git a/src/generators/genpy.ml b/src/generators/genpy.ml index 95c162cd63b..e58d05dcc90 100644 --- a/src/generators/genpy.ml +++ b/src/generators/genpy.ml @@ -2426,7 +2426,7 @@ module Generator = struct let run com = Transformer.init com; let ctx = mk_context com in - Gctx_todo.map_source_header com.defines (fun s -> print ctx "# %s\n# coding: utf-8\n" s); + Gctx.map_source_header com.defines (fun s -> print ctx "# %s\n# coding: utf-8\n" s); if has_feature ctx "closure_Array" || has_feature ctx "closure_String" then spr ctx "from functools import partial as _hx_partial\n"; spr ctx "import sys\n"; diff --git a/src/generators/genswf.ml b/src/generators/genswf.ml index 8aed80733f9..5b594b7b9e6 100644 --- a/src/generators/genswf.ml +++ b/src/generators/genswf.ml @@ -276,9 +276,8 @@ let build_swf9 com file swc = classes := { f9_cid = Some !cid; f9_classname = s_type_path (Genswf9.resource_path name) } :: !classes; tag (TBinaryData (!cid,data)) :: acc ) com.resources [] in - let find_file f = (com.class_paths#find_file f).file in let load_file_data file p = - let file = try find_file file with Not_found -> file in + let file = try Gctx.find_file com file with Not_found -> file in if String.length file > 5 && String.sub file 0 5 = "data:" then String.sub file 5 (String.length file - 5) else @@ -578,8 +577,7 @@ let generate swf_header swf_libs flash_version com = let meta_data = try let file = Gctx.defined_value com Define.SwfMetadata in - let find_file f = (com.class_paths#find_file f).file in - let file = try find_file file with Not_found -> file in + let file = try Gctx.find_file com file with Not_found -> file in let data = try Std.input_file ~bin:true file with Sys_error _ -> failwith ("Metadata resource file not found : " ^ file) in [tag(TMetaData (data))] with Not_found -> diff --git a/src/generators/hl2c.ml b/src/generators/hl2c.ml index b716ee5ebc1..ea3989ed4a7 100644 --- a/src/generators/hl2c.ml +++ b/src/generators/hl2c.ml @@ -345,7 +345,7 @@ let short_digest str = let open_file ctx file = if ctx.curfile <> "" then close_file ctx; if file <> "hlc.json" then - Gctx_todo.map_source_header ctx.gcon.defines (fun s -> define ctx (sprintf "// %s" s)); + Gctx.map_source_header ctx.gcon.defines (fun s -> define ctx (sprintf "// %s" s)); ctx.curfile <- file; ctx.fun_index <- 0; ctx.file_prefix <- (short_digest file) ^ "_" diff --git a/src/typing/macroContext.ml b/src/typing/macroContext.ml index 5bb19058c6f..7b5c23f3e6e 100644 --- a/src/typing/macroContext.ml +++ b/src/typing/macroContext.ml @@ -211,7 +211,7 @@ let make_macro_com_api com mcom p = set_js_generator = (fun gen -> com.js_gen <- Some (fun() -> Path.mkdir_from_path com.file; - let js_ctx = Genjs.alloc_ctx (Common.to_gctx com) (Gctx_todo.get_es_version com.defines) in + let js_ctx = Genjs.alloc_ctx (Common.to_gctx com) (Gctx.get_es_version com.defines) in let t = macro_timer com ["jsGenerator"] in gen js_ctx; t()