authorgravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2019-11-26 10:27:51+02:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2019-11-26 11:52:12+02:00
log36849d8a7b5b0ed62d966ea9c402f192ade0cadf
treeb03def98fe255f4572add7e7cae155e07964e93c
parent76f21852f6553fc22612bb82df19184fdb28719e
signaturelock-open Commit is signed but in an unrecognized format.

fixes and cleanup in self hosted


12 files changed, 244 insertions(+), 302 deletions(-)

src-self-hosted/codegen.zig+15-15
......@@ -25,10 +25,10 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
2525
2626 const context = llvm_handle.node.data;
2727
28 const module = llvm.ModuleCreateWithNameInContext(comp.name.ptr(), context) orelse return error.OutOfMemory;
28 const module = llvm.ModuleCreateWithNameInContext(comp.name.toSliceConst(), context) orelse return error.OutOfMemory;
2929 defer llvm.DisposeModule(module);
3030
31 llvm.SetTarget(module, comp.llvm_triple.ptr());
31 llvm.SetTarget(module, comp.llvm_triple.toSliceConst());
3232 llvm.SetDataLayout(module, comp.target_layout_str);
3333
3434 if (util.getObjectFormat(comp.target) == .coff) {
......@@ -48,23 +48,23 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
4848 const producer = try std.Buffer.allocPrint(
4949 &code.arena.allocator,
5050 "zig {}.{}.{}",
51 u32(c.ZIG_VERSION_MAJOR),
52 u32(c.ZIG_VERSION_MINOR),
53 u32(c.ZIG_VERSION_PATCH),
51 @as(u32, c.ZIG_VERSION_MAJOR),
52 @as(u32, c.ZIG_VERSION_MINOR),
53 @as(u32, c.ZIG_VERSION_PATCH),
5454 );
5555 const flags = "";
5656 const runtime_version = 0;
5757 const compile_unit_file = llvm.CreateFile(
5858 dibuilder,
59 comp.name.ptr(),
60 comp.root_package.root_src_dir.ptr(),
59 comp.name.toSliceConst(),
60 comp.root_package.root_src_dir.toSliceConst(),
6161 ) orelse return error.OutOfMemory;
6262 const is_optimized = comp.build_mode != .Debug;
6363 const compile_unit = llvm.CreateCompileUnit(
6464 dibuilder,
6565 DW.LANG_C99,
6666 compile_unit_file,
67 producer.ptr(),
67 producer.toSliceConst(),
6868 is_optimized,
6969 flags,
7070 runtime_version,
......@@ -99,7 +99,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
9999
100100 // verify the llvm module when safety is on
101101 if (std.debug.runtime_safety) {
102 var error_ptr: ?[*]u8 = null;
102 var error_ptr: ?[*:0]u8 = null;
103103 _ = llvm.VerifyModule(ofile.module, llvm.AbortProcessAction, &error_ptr);
104104 }
105105
......@@ -108,12 +108,12 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
108108 const is_small = comp.build_mode == .ReleaseSmall;
109109 const is_debug = comp.build_mode == .Debug;
110110
111 var err_msg: [*]u8 = undefined;
111 var err_msg: [*:0]u8 = undefined;
112112 // TODO integrate this with evented I/O
113113 if (llvm.TargetMachineEmitToFile(
114114 comp.target_machine,
115115 module,
116 output_path.ptr(),
116 output_path.toSliceConst(),
117117 llvm.EmitBinary,
118118 &err_msg,
119119 is_debug,
......@@ -154,7 +154,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code)
154154 const llvm_fn_type = try fn_val.base.typ.getLlvmType(ofile.arena, ofile.context);
155155 const llvm_fn = llvm.AddFunction(
156156 ofile.module,
157 fn_val.symbol_name.ptr(),
157 fn_val.symbol_name.toSliceConst(),
158158 llvm_fn_type,
159159 ) orelse return error.OutOfMemory;
160160
......@@ -379,7 +379,7 @@ fn renderLoadUntyped(
379379 ptr: *llvm.Value,
380380 alignment: Type.Pointer.Align,
381381 vol: Type.Pointer.Vol,
382 name: [*]const u8,
382 name: [*:0]const u8,
383383) !*llvm.Value {
384384 const result = llvm.BuildLoad(ofile.builder, ptr, name) orelse return error.OutOfMemory;
385385 switch (vol) {
......@@ -390,7 +390,7 @@ fn renderLoadUntyped(
390390 return result;
391391}
392392
393fn renderLoad(ofile: *ObjectFile, ptr: *llvm.Value, ptr_type: *Type.Pointer, name: [*]const u8) !*llvm.Value {
393fn renderLoad(ofile: *ObjectFile, ptr: *llvm.Value, ptr_type: *Type.Pointer, name: [*:0]const u8) !*llvm.Value {
394394 return renderLoadUntyped(ofile, ptr, ptr_type.key.alignment, ptr_type.key.vol, name);
395395}
396396
......@@ -438,7 +438,7 @@ pub fn renderAlloca(
438438) !*llvm.Value {
439439 const llvm_var_type = try var_type.getLlvmType(ofile.arena, ofile.context);
440440 const name_with_null = try std.cstr.addNullByte(ofile.arena, name);
441 const result = llvm.BuildAlloca(ofile.builder, llvm_var_type, name_with_null.ptr) orelse return error.OutOfMemory;
441 const result = llvm.BuildAlloca(ofile.builder, llvm_var_type, @ptrCast([*:0]const u8, name_with_null.ptr)) orelse return error.OutOfMemory;
442442 llvm.SetAlignment(result, resolveAlign(ofile, alignment, llvm_var_type));
443443 return result;
444444}
src-self-hosted/compilation.zig+93-128
......@@ -93,7 +93,7 @@ pub const ZigCompiler = struct {
9393 return LlvmHandle{ .node = node };
9494 }
9595
96 pub async fn getNativeLibC(self: *ZigCompiler) !*LibCInstallation {
96 pub fn getNativeLibC(self: *ZigCompiler) !*LibCInstallation {
9797 if (self.native_libc.start()) |ptr| return ptr;
9898 try self.native_libc.data.findNative(self.allocator);
9999 self.native_libc.resolve();
......@@ -135,26 +135,26 @@ pub const Compilation = struct {
135135 /// lazily created when we need it
136136 tmp_dir: event.Future(BuildError![]u8),
137137
138 version_major: u32,
139 version_minor: u32,
140 version_patch: u32,
138 version_major: u32 = 0,
139 version_minor: u32 = 0,
140 version_patch: u32 = 0,
141141
142 linker_script: ?[]const u8,
143 out_h_path: ?[]const u8,
142 linker_script: ?[]const u8 = null,
143 out_h_path: ?[]const u8 = null,
144144
145 is_test: bool,
146 each_lib_rpath: bool,
147 strip: bool,
145 is_test: bool = false,
146 each_lib_rpath: bool = false,
147 strip: bool = false,
148148 is_static: bool,
149 linker_rdynamic: bool,
149 linker_rdynamic: bool = false,
150150
151 clang_argv: []const []const u8,
152 lib_dirs: []const []const u8,
153 rpath_list: []const []const u8,
154 assembly_files: []const []const u8,
151 clang_argv: []const []const u8 = [_][]const u8{},
152 lib_dirs: []const []const u8 = [_][]const u8{},
153 rpath_list: []const []const u8 = [_][]const u8{},
154 assembly_files: []const []const u8 = [_][]const u8{},
155155
156156 /// paths that are explicitly provided by the user to link against
157 link_objects: []const []const u8,
157 link_objects: []const []const u8 = [_][]const u8{},
158158
159159 /// functions that have their own objects that we need to link
160160 /// it uses an optional pointer so that tombstone removals are possible
......@@ -162,33 +162,33 @@ pub const Compilation = struct {
162162
163163 pub const FnLinkSet = std.TailQueue(?*Value.Fn);
164164
165 windows_subsystem_windows: bool,
166 windows_subsystem_console: bool,
165 windows_subsystem_windows: bool = false,
166 windows_subsystem_console: bool = false,
167167
168168 link_libs_list: ArrayList(*LinkLib),
169 libc_link_lib: ?*LinkLib,
169 libc_link_lib: ?*LinkLib = null,
170170
171 err_color: errmsg.Color,
171 err_color: errmsg.Color = .Auto,
172172
173 verbose_tokenize: bool,
174 verbose_ast_tree: bool,
175 verbose_ast_fmt: bool,
176 verbose_cimport: bool,
177 verbose_ir: bool,
178 verbose_llvm_ir: bool,
179 verbose_link: bool,
173 verbose_tokenize: bool = false,
174 verbose_ast_tree: bool = false,
175 verbose_ast_fmt: bool = false,
176 verbose_cimport: bool = false,
177 verbose_ir: bool = false,
178 verbose_llvm_ir: bool = false,
179 verbose_link: bool = false,
180180
181 darwin_frameworks: []const []const u8,
182 darwin_version_min: DarwinVersionMin,
181 darwin_frameworks: []const []const u8 = [_][]const u8{},
182 darwin_version_min: DarwinVersionMin = .None,
183183
184 test_filters: []const []const u8,
185 test_name_prefix: ?[]const u8,
184 test_filters: []const []const u8 = [_][]const u8{},
185 test_name_prefix: ?[]const u8 = null,
186186
187 emit_file_type: Emit,
187 emit_file_type: Emit = .Binary,
188188
189189 kind: Kind,
190190
191 link_out_file: ?[]const u8,
191 link_out_file: ?[]const u8 = null,
192192 events: *event.Channel(Event),
193193
194194 exported_symbol_names: event.Locked(Decl.Table),
......@@ -213,7 +213,7 @@ pub const Compilation = struct {
213213
214214 target_machine: *llvm.TargetMachine,
215215 target_data_ref: *llvm.TargetData,
216 target_layout_str: [*]u8,
216 target_layout_str: [*:0]u8,
217217 target_ptr_bits: u32,
218218
219219 /// for allocating things which have the same lifetime as this Compilation
......@@ -222,7 +222,7 @@ pub const Compilation = struct {
222222 root_package: *Package,
223223 std_package: *Package,
224224
225 override_libc: ?*LibCInstallation,
225 override_libc: ?*LibCInstallation = null,
226226
227227 /// need to wait on this group before deinitializing
228228 deinit_group: event.Group(void),
......@@ -231,7 +231,7 @@ pub const Compilation = struct {
231231 // main_loop_frame: @Frame(Compilation.mainLoop),
232232 main_loop_future: event.Future(void),
233233
234 have_err_ret_tracing: bool,
234 have_err_ret_tracing: bool = false,
235235
236236 /// not locked because it is read-only
237237 primitive_type_table: TypeTable,
......@@ -243,7 +243,7 @@ pub const Compilation = struct {
243243
244244 c_int_types: [CInt.list.len]*Type.Int,
245245
246 // fs_watch: *fs.Watch(*Scope.Root),
246 fs_watch: *fs.Watch(*Scope.Root),
247247
248248 const IntTypeTable = std.HashMap(*const Type.Int.Key, *Type.Int, Type.Int.Key.hash, Type.Int.Key.eql);
249249 const ArrayTypeTable = std.HashMap(*const Type.Array.Key, *Type.Array, Type.Array.Key.hash, Type.Array.Key.eql);
......@@ -392,43 +392,10 @@ pub const Compilation = struct {
392392
393393 .name = undefined,
394394 .llvm_triple = undefined,
395
396 .version_major = 0,
397 .version_minor = 0,
398 .version_patch = 0,
399
400 .verbose_tokenize = false,
401 .verbose_ast_tree = false,
402 .verbose_ast_fmt = false,
403 .verbose_cimport = false,
404 .verbose_ir = false,
405 .verbose_llvm_ir = false,
406 .verbose_link = false,
407
408 .linker_script = null,
409 .out_h_path = null,
410 .is_test = false,
411 .each_lib_rpath = false,
412 .strip = false,
413395 .is_static = is_static,
414 .linker_rdynamic = false,
415 .clang_argv = [_][]const u8{},
416 .lib_dirs = [_][]const u8{},
417 .rpath_list = [_][]const u8{},
418 .assembly_files = [_][]const u8{},
419 .link_objects = [_][]const u8{},
420396 .fn_link_set = event.Locked(FnLinkSet).init(FnLinkSet.init()),
421 .windows_subsystem_windows = false,
422 .windows_subsystem_console = false,
423397 .link_libs_list = undefined,
424 .libc_link_lib = null,
425 .err_color = errmsg.Color.Auto,
426 .darwin_frameworks = [_][]const u8{},
427 .darwin_version_min = DarwinVersionMin.None,
428 .test_filters = [_][]const u8{},
429 .test_name_prefix = null,
430 .emit_file_type = Emit.Binary,
431 .link_out_file = null,
398
432399 .exported_symbol_names = event.Locked(Decl.Table).init(Decl.Table.init(allocator)),
433400 .prelink_group = event.Group(BuildError!void).init(allocator),
434401 .deinit_group = event.Group(void).init(allocator),
......@@ -458,11 +425,9 @@ pub const Compilation = struct {
458425 .root_package = undefined,
459426 .std_package = undefined,
460427
461 .override_libc = null,
462 .have_err_ret_tracing = false,
463428 .primitive_type_table = undefined,
464429
465 // .fs_watch = undefined,
430 .fs_watch = undefined,
466431 };
467432 comp.link_libs_list = ArrayList(*LinkLib).init(comp.arena());
468433 comp.primitive_type_table = TypeTable.init(comp.arena());
......@@ -534,8 +499,8 @@ pub const Compilation = struct {
534499 comp.root_package = try Package.create(comp.arena(), ".", "");
535500 }
536501
537 // comp.fs_watch = try fs.Watch(*Scope.Root).create(16);
538 // defer comp.fs_watch.destroy();
502 comp.fs_watch = try fs.Watch(*Scope.Root).init(allocator, 16);
503 defer comp.fs_watch.deinit();
539504
540505 try comp.initTypes();
541506 defer comp.primitive_type_table.deinit();
......@@ -559,7 +524,7 @@ pub const Compilation = struct {
559524 }
560525
561526 /// it does ref the result because it could be an arbitrary integer size
562 pub async fn getPrimitiveType(comp: *Compilation, name: []const u8) !?*Type {
527 pub fn getPrimitiveType(comp: *Compilation, name: []const u8) !?*Type {
563528 if (name.len >= 2) {
564529 switch (name[0]) {
565530 'i', 'u' => blk: {
......@@ -795,47 +760,47 @@ pub const Compilation = struct {
795760 self.events.put(Event{ .Error = err });
796761 }
797762
798 // // First, get an item from the watch channel, waiting on the channel.
799 // var group = event.Group(BuildError!void).init(self.gpa());
800 // {
801 // const ev = (self.fs_watch.channel.get()) catch |err| {
802 // build_result = err;
803 // continue;
804 // };
805 // const root_scope = ev.data;
806 // group.call(rebuildFile, self, root_scope) catch |err| {
807 // build_result = err;
808 // continue;
809 // };
810 // }
811 // // Next, get all the items from the channel that are buffered up.
812 // while (self.fs_watch.channel.getOrNull()) |ev_or_err| {
813 // if (ev_or_err) |ev| {
814 // const root_scope = ev.data;
815 // group.call(rebuildFile, self, root_scope) catch |err| {
816 // build_result = err;
817 // continue;
818 // };
819 // } else |err| {
820 // build_result = err;
821 // continue;
822 // }
823 // }
824 // build_result = group.wait();
763 // First, get an item from the watch channel, waiting on the channel.
764 var group = event.Group(BuildError!void).init(self.gpa());
765 {
766 const ev = (self.fs_watch.channel.get()) catch |err| {
767 build_result = err;
768 continue;
769 };
770 const root_scope = ev.data;
771 group.call(rebuildFile, self, root_scope) catch |err| {
772 build_result = err;
773 continue;
774 };
775 }
776 // Next, get all the items from the channel that are buffered up.
777 while (self.fs_watch.channel.getOrNull()) |ev_or_err| {
778 if (ev_or_err) |ev| {
779 const root_scope = ev.data;
780 group.call(rebuildFile, self, root_scope) catch |err| {
781 build_result = err;
782 continue;
783 };
784 } else |err| {
785 build_result = err;
786 continue;
787 }
788 }
789 build_result = group.wait();
825790 }
826791 }
827792
828 async fn rebuildFile(self: *Compilation, root_scope: *Scope.Root) !void {
793 async fn rebuildFile(self: *Compilation, root_scope: *Scope.Root) BuildError!void {
829794 const tree_scope = blk: {
830 const source_code = "";
831 // const source_code = fs.readFile(
832 // root_scope.realpath,
833 // max_src_size,
834 // ) catch |err| {
835 // try self.addCompileErrorCli(root_scope.realpath, "unable to open: {}", @errorName(err));
836 // return;
837 // };
838 // errdefer self.gpa().free(source_code);
795 const source_code = fs.readFile(
796 self.gpa(),
797 root_scope.realpath,
798 max_src_size,
799 ) catch |err| {
800 try self.addCompileErrorCli(root_scope.realpath, "unable to open: {}", @errorName(err));
801 return;
802 };
803 errdefer self.gpa().free(source_code);
839804
840805 const tree = try std.zig.parse(self.gpa(), source_code);
841806 errdefer {
......@@ -873,7 +838,7 @@ pub const Compilation = struct {
873838 try decl_group.wait();
874839 }
875840
876 async fn rebuildChangedDecls(
841 fn rebuildChangedDecls(
877842 self: *Compilation,
878843 group: *event.Group(BuildError!void),
879844 locked_table: *Decl.Table,
......@@ -962,7 +927,7 @@ pub const Compilation = struct {
962927 }
963928 }
964929
965 async fn initialCompile(self: *Compilation) !void {
930 fn initialCompile(self: *Compilation) !void {
966931 if (self.root_src_path) |root_src_path| {
967932 const root_scope = blk: {
968933 // TODO async/await std.fs.realpath
......@@ -981,7 +946,7 @@ pub const Compilation = struct {
981946 }
982947 }
983948
984 async fn maybeLink(self: *Compilation) !void {
949 fn maybeLink(self: *Compilation) !void {
985950 (self.prelink_group.wait()) catch |err| switch (err) {
986951 error.SemanticAnalysisFailed => {},
987952 else => return err,
......@@ -1184,7 +1149,7 @@ pub const Compilation = struct {
11841149
11851150 /// If the temporary directory for this compilation has not been created, it creates it.
11861151 /// Then it creates a random file name in that dir and returns it.
1187 pub async fn createRandomOutputPath(self: *Compilation, suffix: []const u8) !Buffer {
1152 pub fn createRandomOutputPath(self: *Compilation, suffix: []const u8) !Buffer {
11881153 const tmp_dir = try self.getTmpDir();
11891154 const file_prefix = self.getRandomFileName();
11901155
......@@ -1200,14 +1165,14 @@ pub const Compilation = struct {
12001165 /// If the temporary directory for this Compilation has not been created, creates it.
12011166 /// Then returns it. The directory is unique to this Compilation and cleaned up when
12021167 /// the Compilation deinitializes.
1203 async fn getTmpDir(self: *Compilation) ![]const u8 {
1168 fn getTmpDir(self: *Compilation) ![]const u8 {
12041169 if (self.tmp_dir.start()) |ptr| return ptr.*;
12051170 self.tmp_dir.data = self.getTmpDirImpl();
12061171 self.tmp_dir.resolve();
12071172 return self.tmp_dir.data;
12081173 }
12091174
1210 async fn getTmpDirImpl(self: *Compilation) ![]u8 {
1175 fn getTmpDirImpl(self: *Compilation) ![]u8 {
12111176 const comp_dir_name = self.getRandomFileName();
12121177 const zig_dir_path = try getZigDir(self.gpa());
12131178 defer self.gpa().free(zig_dir_path);
......@@ -1217,7 +1182,7 @@ pub const Compilation = struct {
12171182 return tmp_dir;
12181183 }
12191184
1220 async fn getRandomFileName(self: *Compilation) [12]u8 {
1185 fn getRandomFileName(self: *Compilation) [12]u8 {
12211186 // here we replace the standard +/ with -_ so that it can be used in a file name
12221187 const b64_fs_encoder = std.base64.Base64Encoder.init(
12231188 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
......@@ -1243,7 +1208,7 @@ pub const Compilation = struct {
12431208 }
12441209
12451210 /// Returns a value which has been ref()'d once
1246 async fn analyzeConstValue(
1211 fn analyzeConstValue(
12471212 comp: *Compilation,
12481213 tree_scope: *Scope.AstTree,
12491214 scope: *Scope,
......@@ -1256,7 +1221,7 @@ pub const Compilation = struct {
12561221 return analyzed_code.getCompTimeResult(comp);
12571222 }
12581223
1259 async fn analyzeTypeExpr(comp: *Compilation, tree_scope: *Scope.AstTree, scope: *Scope, node: *ast.Node) !*Type {
1224 fn analyzeTypeExpr(comp: *Compilation, tree_scope: *Scope.AstTree, scope: *Scope, node: *ast.Node) !*Type {
12601225 const meta_type = &Type.MetaType.get(comp).base;
12611226 defer meta_type.base.deref(comp);
12621227
......@@ -1287,7 +1252,7 @@ fn parseVisibToken(tree: *ast.Tree, optional_token_index: ?ast.TokenIndex) Visib
12871252}
12881253
12891254/// The function that actually does the generation.
1290async fn generateDecl(comp: *Compilation, decl: *Decl) !void {
1255fn generateDecl(comp: *Compilation, decl: *Decl) !void {
12911256 switch (decl.id) {
12921257 .Var => @panic("TODO"),
12931258 .Fn => {
......@@ -1298,7 +1263,7 @@ async fn generateDecl(comp: *Compilation, decl: *Decl) !void {
12981263 }
12991264}
13001265
1301async fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void {
1266fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void {
13021267 const tree_scope = fn_decl.base.tree_scope;
13031268
13041269 const body_node = fn_decl.fn_proto.body_node orelse return generateDeclFnProto(comp, fn_decl);
......@@ -1315,7 +1280,7 @@ async fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void {
13151280
13161281 // The Decl.Fn owns the initial 1 reference count
13171282 const fn_val = try Value.Fn.create(comp, fn_type, fndef_scope, symbol_name);
1318 fn_decl.value = Decl.Fn.Val{ .Fn = fn_val };
1283 fn_decl.value = .{ .Fn = fn_val };
13191284 symbol_name_consumed = true;
13201285
13211286 // Define local parameter variables
......@@ -1382,7 +1347,7 @@ fn getZigDir(allocator: *mem.Allocator) ![]u8 {
13821347 return std.fs.getAppDataDir(allocator, "zig");
13831348}
13841349
1385async fn analyzeFnType(
1350fn analyzeFnType(
13861351 comp: *Compilation,
13871352 tree_scope: *Scope.AstTree,
13881353 scope: *Scope,
......@@ -1444,7 +1409,7 @@ async fn analyzeFnType(
14441409 return fn_type;
14451410}
14461411
1447async fn generateDeclFnProto(comp: *Compilation, fn_decl: *Decl.Fn) !void {
1412fn generateDeclFnProto(comp: *Compilation, fn_decl: *Decl.Fn) !void {
14481413 const fn_type = try analyzeFnType(
14491414 comp,
14501415 fn_decl.base.tree_scope,
......@@ -1459,6 +1424,6 @@ async fn generateDeclFnProto(comp: *Compilation, fn_decl: *Decl.Fn) !void {
14591424
14601425 // The Decl.Fn owns the initial 1 reference count
14611426 const fn_proto_val = try Value.FnProto.create(comp, fn_type, symbol_name);
1462 fn_decl.value = Decl.Fn.Val{ .FnProto = fn_proto_val };
1427 fn_decl.value = .{ .FnProto = fn_proto_val };
14631428 symbol_name_consumed = true;
14641429}
src-self-hosted/decl.zig+3-6
......@@ -69,15 +69,12 @@ pub const Decl = struct {
6969
7070 pub const Fn = struct {
7171 base: Decl,
72 value: Val,
73 fn_proto: *ast.Node.FnProto,
74
75 // TODO https://github.com/ziglang/zig/issues/683 and then make this anonymous
76 pub const Val = union(enum) {
72 value: union(enum) {
7773 Unresolved,
7874 Fn: *Value.Fn,
7975 FnProto: *Value.FnProto,
80 };
76 },
77 fn_proto: *ast.Node.FnProto,
8178
8279 pub fn externLibName(self: Fn, tree: *ast.Tree) ?[]const u8 {
8380 return if (self.fn_proto.extern_export_inline_token) |tok_index| x: {
src-self-hosted/ir.zig+22-21
......@@ -110,7 +110,7 @@ pub const Inst = struct {
110110 unreachable;
111111 }
112112
113 pub async fn analyze(base: *Inst, ira: *Analyze) Analyze.Error!*Inst {
113 pub fn analyze(base: *Inst, ira: *Analyze) Analyze.Error!*Inst {
114114 switch (base.id) {
115115 .Return => return @fieldParentPtr(Return, "base", base).analyze(ira),
116116 .Const => return @fieldParentPtr(Const, "base", base).analyze(ira),
......@@ -422,7 +422,7 @@ pub const Inst = struct {
422422 return false;
423423 }
424424
425 pub async fn analyze(self: *const Ref, ira: *Analyze) !*Inst {
425 pub fn analyze(self: *const Ref, ira: *Analyze) !*Inst {
426426 const target = try self.params.target.getAsParam();
427427
428428 if (ira.getCompTimeValOrNullUndefOk(target)) |val| {
......@@ -472,7 +472,7 @@ pub const Inst = struct {
472472 return false;
473473 }
474474
475 pub async fn analyze(self: *const DeclRef, ira: *Analyze) !*Inst {
475 pub fn analyze(self: *const DeclRef, ira: *Analyze) !*Inst {
476476 (ira.irb.comp.resolveDecl(self.params.decl)) catch |err| switch (err) {
477477 error.OutOfMemory => return error.OutOfMemory,
478478 else => return error.SemanticAnalysisFailed,
......@@ -516,7 +516,7 @@ pub const Inst = struct {
516516 return false;
517517 }
518518
519 pub async fn analyze(self: *const VarPtr, ira: *Analyze) !*Inst {
519 pub fn analyze(self: *const VarPtr, ira: *Analyze) !*Inst {
520520 switch (self.params.var_scope.data) {
521521 .Const => @panic("TODO"),
522522 .Param => |param| {
......@@ -563,7 +563,7 @@ pub const Inst = struct {
563563 return false;
564564 }
565565
566 pub async fn analyze(self: *const LoadPtr, ira: *Analyze) !*Inst {
566 pub fn analyze(self: *const LoadPtr, ira: *Analyze) !*Inst {
567567 const target = try self.params.target.getAsParam();
568568 const target_type = target.getKnownType();
569569 if (target_type.id != .Pointer) {
......@@ -645,7 +645,7 @@ pub const Inst = struct {
645645 return false;
646646 }
647647
648 pub async fn analyze(self: *const PtrType, ira: *Analyze) !*Inst {
648 pub fn analyze(self: *const PtrType, ira: *Analyze) !*Inst {
649649 const child_type = try self.params.child_type.getAsConstType(ira);
650650 // if (child_type->id == TypeTableEntryIdUnreachable) {
651651 // ir_add_error(ira, &instruction->base, buf_sprintf("pointer to noreturn not allowed"));
......@@ -927,7 +927,7 @@ pub const Variable = struct {
927927
928928pub const BasicBlock = struct {
929929 ref_count: usize,
930 name_hint: [*]const u8, // must be a C string literal
930 name_hint: [*:0]const u8,
931931 debug_id: usize,
932932 scope: *Scope,
933933 instruction_list: std.ArrayList(*Inst),
......@@ -1051,7 +1051,7 @@ pub const Builder = struct {
10511051 }
10521052
10531053 /// No need to clean up resources thanks to the arena allocator.
1054 pub fn createBasicBlock(self: *Builder, scope: *Scope, name_hint: [*]const u8) !*BasicBlock {
1054 pub fn createBasicBlock(self: *Builder, scope: *Scope, name_hint: [*:0]const u8) !*BasicBlock {
10551055 const basic_block = try self.arena().create(BasicBlock);
10561056 basic_block.* = BasicBlock{
10571057 .ref_count = 0,
......@@ -1186,6 +1186,7 @@ pub const Builder = struct {
11861186 }
11871187 }
11881188
1189 fn genCall(irb: *Builder, suffix_op: *ast.Node.SuffixOp, call: *ast.Node.SuffixOp.Op.Call, scope: *Scope) !*Inst {
11891190 async fn genCall(irb: *Builder, suffix_op: *ast.Node.SuffixOp, call: *ast.Node.SuffixOp.Op.Call, scope: *Scope) !*Inst {
11901191 const fn_ref = try irb.genNode(suffix_op.lhs, scope, .None);
11911192
......@@ -1214,7 +1215,7 @@ pub const Builder = struct {
12141215 //return ir_lval_wrap(irb, scope, fn_call, lval);
12151216 }
12161217
1217 async fn genPtrType(
1218 fn genPtrType(
12181219 irb: *Builder,
12191220 prefix_op: *ast.Node.PrefixOp,
12201221 ptr_info: ast.Node.PrefixOp.PtrInfo,
......@@ -1307,9 +1308,9 @@ pub const Builder = struct {
13071308 var rest: []const u8 = undefined;
13081309 if (int_token.len >= 3 and int_token[0] == '0') {
13091310 base = switch (int_token[1]) {
1310 'b' => u8(2),
1311 'o' => u8(8),
1312 'x' => u8(16),
1311 'b' => 2,
1312 'o' => 8,
1313 'x' => 16,
13131314 else => unreachable,
13141315 };
13151316 rest = int_token[2..];
......@@ -1339,7 +1340,7 @@ pub const Builder = struct {
13391340 return inst;
13401341 }
13411342
1342 pub async fn genStrLit(irb: *Builder, str_lit: *ast.Node.StringLiteral, scope: *Scope) !*Inst {
1343 pub fn genStrLit(irb: *Builder, str_lit: *ast.Node.StringLiteral, scope: *Scope) !*Inst {
13431344 const str_token = irb.code.tree_scope.tree.tokenSlice(str_lit.token);
13441345 const src_span = Span.token(str_lit.token);
13451346
......@@ -1389,7 +1390,7 @@ pub const Builder = struct {
13891390 }
13901391 }
13911392
1392 pub async fn genBlock(irb: *Builder, block: *ast.Node.Block, parent_scope: *Scope) !*Inst {
1393 pub fn genBlock(irb: *Builder, block: *ast.Node.Block, parent_scope: *Scope) !*Inst {
13931394 const block_scope = try Scope.Block.create(irb.comp, parent_scope);
13941395
13951396 const outer_block_scope = &block_scope.base;
......@@ -1499,7 +1500,7 @@ pub const Builder = struct {
14991500 return irb.buildConstVoid(child_scope, Span.token(block.rbrace), true);
15001501 }
15011502
1502 pub async fn genControlFlowExpr(
1503 pub fn genControlFlowExpr(
15031504 irb: *Builder,
15041505 control_flow_expr: *ast.Node.ControlFlowExpression,
15051506 scope: *Scope,
......@@ -1596,7 +1597,7 @@ pub const Builder = struct {
15961597 }
15971598 }
15981599
1599 pub async fn genIdentifier(irb: *Builder, identifier: *ast.Node.Identifier, scope: *Scope, lval: LVal) !*Inst {
1600 pub fn genIdentifier(irb: *Builder, identifier: *ast.Node.Identifier, scope: *Scope, lval: LVal) !*Inst {
16001601 const src_span = Span.token(identifier.token);
16011602 const name = irb.code.tree_scope.tree.tokenSlice(identifier.token);
16021603
......@@ -1694,7 +1695,7 @@ pub const Builder = struct {
16941695 return result;
16951696 }
16961697
1697 async fn genDefersForBlock(
1698 fn genDefersForBlock(
16981699 irb: *Builder,
16991700 inner_scope: *Scope,
17001701 outer_scope: *Scope,
......@@ -1797,7 +1798,7 @@ pub const Builder = struct {
17971798 // Look at the params and ref() other instructions
17981799 comptime var i = 0;
17991800 inline while (i < @memberCount(I.Params)) : (i += 1) {
1800 const FieldType = comptime @typeOf(@field(I.Params(undefined), @memberName(I.Params, i)));
1801 const FieldType = comptime @typeOf(@field(@as(I.Params, undefined), @memberName(I.Params, i)));
18011802 switch (FieldType) {
18021803 *Inst => @field(inst.params, @memberName(I.Params, i)).ref(self),
18031804 *BasicBlock => @field(inst.params, @memberName(I.Params, i)).ref(self),
......@@ -1909,7 +1910,7 @@ pub const Builder = struct {
19091910 VarScope: *Scope.Var,
19101911 };
19111912
1912 async fn findIdent(irb: *Builder, scope: *Scope, name: []const u8) Ident {
1913 fn findIdent(irb: *Builder, scope: *Scope, name: []const u8) Ident {
19131914 var s = scope;
19141915 while (true) {
19151916 switch (s.id) {
......@@ -2519,7 +2520,7 @@ const Analyze = struct {
25192520 }
25202521};
25212522
2522pub async fn gen(
2523pub fn gen(
25232524 comp: *Compilation,
25242525 body_node: *ast.Node,
25252526 tree_scope: *Scope.AstTree,
......@@ -2541,7 +2542,7 @@ pub async fn gen(
25412542 return irb.finish();
25422543}
25432544
2544pub async fn analyze(comp: *Compilation, old_code: *Code, expected_type: ?*Type) !*Code {
2545pub fn analyze(comp: *Compilation, old_code: *Code, expected_type: ?*Type) !*Code {
25452546 const old_entry_bb = old_code.basic_block_list.at(0);
25462547
25472548 var ira = try Analyze.init(comp, old_code.tree_scope, expected_type);
src-self-hosted/libc_installation.zig+2-2
......@@ -143,7 +143,7 @@ pub const LibCInstallation = struct {
143143 }
144144
145145 /// Finds the default, native libc.
146 pub async fn findNative(self: *LibCInstallation, allocator: *Allocator) !void {
146 pub fn findNative(self: *LibCInstallation, allocator: *Allocator) !void {
147147 self.initEmpty();
148148 var group = event.Group(FindError!void).init(allocator);
149149 errdefer group.wait() catch {};
......@@ -393,7 +393,7 @@ pub const LibCInstallation = struct {
393393};
394394
395395/// caller owns returned memory
396async fn ccPrintFileName(allocator: *Allocator, o_file: []const u8, want_dirname: bool) ![]u8 {
396fn ccPrintFileName(allocator: *Allocator, o_file: []const u8, want_dirname: bool) ![]u8 {
397397 const cc_exe = std.os.getenv("CC") orelse "cc";
398398 const arg1 = try std.fmt.allocPrint(allocator, "-print-file-name={}", o_file);
399399 defer allocator.free(arg1);
src-self-hosted/link.zig+26-29
......@@ -11,7 +11,7 @@ const util = @import("util.zig");
1111const Context = struct {
1212 comp: *Compilation,
1313 arena: std.heap.ArenaAllocator,
14 args: std.ArrayList([*]const u8),
14 args: std.ArrayList([*:0]const u8),
1515 link_in_crt: bool,
1616
1717 link_err: error{OutOfMemory}!void,
......@@ -21,7 +21,7 @@ const Context = struct {
2121 out_file_path: std.Buffer,
2222};
2323
24pub async fn link(comp: *Compilation) !void {
24pub fn link(comp: *Compilation) !void {
2525 var ctx = Context{
2626 .comp = comp,
2727 .arena = std.heap.ArenaAllocator.init(comp.gpa()),
......@@ -33,7 +33,7 @@ pub async fn link(comp: *Compilation) !void {
3333 .out_file_path = undefined,
3434 };
3535 defer ctx.arena.deinit();
36 ctx.args = std.ArrayList([*]const u8).init(&ctx.arena.allocator);
36 ctx.args = std.ArrayList([*:0]const u8).init(&ctx.arena.allocator);
3737 ctx.link_msg = std.Buffer.initNull(&ctx.arena.allocator);
3838
3939 if (comp.link_out_file) |out_file| {
......@@ -171,7 +171,7 @@ fn constructLinkerArgsElf(ctx: *Context) !void {
171171 //}
172172
173173 try ctx.args.append("-o");
174 try ctx.args.append(ctx.out_file_path.ptr());
174 try ctx.args.append(ctx.out_file_path.toSliceConst());
175175
176176 if (ctx.link_in_crt) {
177177 const crt1o = if (ctx.comp.is_static) "crt1.o" else "Scrt1.o";
......@@ -214,10 +214,11 @@ fn constructLinkerArgsElf(ctx: *Context) !void {
214214
215215 if (ctx.comp.haveLibC()) {
216216 try ctx.args.append("-L");
217 try ctx.args.append((try std.cstr.addNullByte(&ctx.arena.allocator, ctx.libc.lib_dir.?)).ptr);
217 // TODO addNullByte should probably return [:0]u8
218 try ctx.args.append(@ptrCast([*:0]const u8, (try std.cstr.addNullByte(&ctx.arena.allocator, ctx.libc.lib_dir.?)).ptr));
218219
219220 try ctx.args.append("-L");
220 try ctx.args.append((try std.cstr.addNullByte(&ctx.arena.allocator, ctx.libc.static_lib_dir.?)).ptr);
221 try ctx.args.append(@ptrCast([*:0]const u8, (try std.cstr.addNullByte(&ctx.arena.allocator, ctx.libc.static_lib_dir.?)).ptr));
221222
222223 if (!ctx.comp.is_static) {
223224 const dl = blk: {
......@@ -226,7 +227,7 @@ fn constructLinkerArgsElf(ctx: *Context) !void {
226227 return error.LibCMissingDynamicLinker;
227228 };
228229 try ctx.args.append("-dynamic-linker");
229 try ctx.args.append((try std.cstr.addNullByte(&ctx.arena.allocator, dl)).ptr);
230 try ctx.args.append(@ptrCast([*:0]const u8, (try std.cstr.addNullByte(&ctx.arena.allocator, dl)).ptr));
230231 }
231232 }
232233
......@@ -238,7 +239,7 @@ fn constructLinkerArgsElf(ctx: *Context) !void {
238239 // .o files
239240 for (ctx.comp.link_objects) |link_object| {
240241 const link_obj_with_null = try std.cstr.addNullByte(&ctx.arena.allocator, link_object);
241 try ctx.args.append(link_obj_with_null.ptr);
242 try ctx.args.append(@ptrCast([*:0]const u8, link_obj_with_null.ptr));
242243 }
243244 try addFnObjects(ctx);
244245
......@@ -313,7 +314,7 @@ fn constructLinkerArgsElf(ctx: *Context) !void {
313314fn addPathJoin(ctx: *Context, dirname: []const u8, basename: []const u8) !void {
314315 const full_path = try std.fs.path.join(&ctx.arena.allocator, [_][]const u8{ dirname, basename });
315316 const full_path_with_null = try std.cstr.addNullByte(&ctx.arena.allocator, full_path);
316 try ctx.args.append(full_path_with_null.ptr);
317 try ctx.args.append(@ptrCast([*:0]const u8, full_path_with_null.ptr));
317318}
318319
319320fn constructLinkerArgsCoff(ctx: *Context) !void {
......@@ -339,12 +340,12 @@ fn constructLinkerArgsCoff(ctx: *Context) !void {
339340 const is_library = ctx.comp.kind == .Lib;
340341
341342 const out_arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-OUT:{}\x00", ctx.out_file_path.toSliceConst());
342 try ctx.args.append(out_arg.ptr);
343 try ctx.args.append(@ptrCast([*:0]const u8, out_arg.ptr));
343344
344345 if (ctx.comp.haveLibC()) {
345 try ctx.args.append((try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", ctx.libc.msvc_lib_dir.?)).ptr);
346 try ctx.args.append((try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", ctx.libc.kernel32_lib_dir.?)).ptr);
347 try ctx.args.append((try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", ctx.libc.lib_dir.?)).ptr);
346 try ctx.args.append(@ptrCast([*:0]const u8, (try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", ctx.libc.msvc_lib_dir.?)).ptr));
347 try ctx.args.append(@ptrCast([*:0]const u8, (try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", ctx.libc.kernel32_lib_dir.?)).ptr));
348 try ctx.args.append(@ptrCast([*:0]const u8, (try std.fmt.allocPrint(&ctx.arena.allocator, "-LIBPATH:{}\x00", ctx.libc.lib_dir.?)).ptr));
348349 }
349350
350351 if (ctx.link_in_crt) {
......@@ -353,17 +354,17 @@ fn constructLinkerArgsCoff(ctx: *Context) !void {
353354
354355 if (ctx.comp.is_static) {
355356 const cmt_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "libcmt{}.lib\x00", d_str);
356 try ctx.args.append(cmt_lib_name.ptr);
357 try ctx.args.append(@ptrCast([*:0]const u8, cmt_lib_name.ptr));
357358 } else {
358359 const msvcrt_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "msvcrt{}.lib\x00", d_str);
359 try ctx.args.append(msvcrt_lib_name.ptr);
360 try ctx.args.append(@ptrCast([*:0]const u8, msvcrt_lib_name.ptr));
360361 }
361362
362363 const vcruntime_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "{}vcruntime{}.lib\x00", lib_str, d_str);
363 try ctx.args.append(vcruntime_lib_name.ptr);
364 try ctx.args.append(@ptrCast([*:0]const u8, vcruntime_lib_name.ptr));
364365
365366 const crt_lib_name = try std.fmt.allocPrint(&ctx.arena.allocator, "{}ucrt{}.lib\x00", lib_str, d_str);
366 try ctx.args.append(crt_lib_name.ptr);
367 try ctx.args.append(@ptrCast([*:0]const u8, crt_lib_name.ptr));
367368
368369 // Visual C++ 2015 Conformance Changes
369370 // https://msdn.microsoft.com/en-us/library/bb531344.aspx
......@@ -395,7 +396,7 @@ fn constructLinkerArgsCoff(ctx: *Context) !void {
395396
396397 for (ctx.comp.link_objects) |link_object| {
397398 const link_obj_with_null = try std.cstr.addNullByte(&ctx.arena.allocator, link_object);
398 try ctx.args.append(link_obj_with_null.ptr);
399 try ctx.args.append(@ptrCast([*:0]const u8, link_obj_with_null.ptr));
399400 }
400401 try addFnObjects(ctx);
401402
......@@ -504,11 +505,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void {
504505 //}
505506
506507 try ctx.args.append("-arch");
507 const darwin_arch_str = try std.cstr.addNullByte(
508 &ctx.arena.allocator,
509 ctx.comp.target.getDarwinArchString(),
510 );
511 try ctx.args.append(darwin_arch_str.ptr);
508 try ctx.args.append(util.getDarwinArchString(ctx.comp.target));
512509
513510 const platform = try DarwinPlatform.get(ctx.comp);
514511 switch (platform.kind) {
......@@ -517,7 +514,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void {
517514 .IPhoneOSSimulator => try ctx.args.append("-ios_simulator_version_min"),
518515 }
519516 const ver_str = try std.fmt.allocPrint(&ctx.arena.allocator, "{}.{}.{}\x00", platform.major, platform.minor, platform.micro);
520 try ctx.args.append(ver_str.ptr);
517 try ctx.args.append(@ptrCast([*:0]const u8, ver_str.ptr));
521518
522519 if (ctx.comp.kind == .Exe) {
523520 if (ctx.comp.is_static) {
......@@ -528,7 +525,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void {
528525 }
529526
530527 try ctx.args.append("-o");
531 try ctx.args.append(ctx.out_file_path.ptr());
528 try ctx.args.append(ctx.out_file_path.toSliceConst());
532529
533530 //for (size_t i = 0; i < g->rpath_list.length; i += 1) {
534531 // Buf *rpath = g->rpath_list.at(i);
......@@ -572,7 +569,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void {
572569
573570 for (ctx.comp.link_objects) |link_object| {
574571 const link_obj_with_null = try std.cstr.addNullByte(&ctx.arena.allocator, link_object);
575 try ctx.args.append(link_obj_with_null.ptr);
572 try ctx.args.append(@ptrCast([*:0]const u8, link_obj_with_null.ptr));
576573 }
577574 try addFnObjects(ctx);
578575
......@@ -593,10 +590,10 @@ fn constructLinkerArgsMachO(ctx: *Context) !void {
593590 } else {
594591 if (mem.indexOfScalar(u8, lib.name, '/') == null) {
595592 const arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-l{}\x00", lib.name);
596 try ctx.args.append(arg.ptr);
593 try ctx.args.append(@ptrCast([*:0]const u8, arg.ptr));
597594 } else {
598595 const arg = try std.cstr.addNullByte(&ctx.arena.allocator, lib.name);
599 try ctx.args.append(arg.ptr);
596 try ctx.args.append(@ptrCast([*:0]const u8, arg.ptr));
600597 }
601598 }
602599 }
......@@ -639,7 +636,7 @@ fn addFnObjects(ctx: *Context) !void {
639636 ctx.comp.gpa().destroy(node);
640637 continue;
641638 };
642 try ctx.args.append(fn_val.containing_object.ptr());
639 try ctx.args.append(fn_val.containing_object.toSliceConst());
643640 it = node.next;
644641 }
645642}
src-self-hosted/llvm.zig+1-1
......@@ -86,7 +86,7 @@ pub const AddGlobal = LLVMAddGlobal;
8686extern fn LLVMAddGlobal(M: *Module, Ty: *Type, Name: [*:0]const u8) ?*Value;
8787
8888pub const ConstStringInContext = LLVMConstStringInContext;
89extern fn LLVMConstStringInContext(C: *Context, Str: [*:0]const u8, Length: c_uint, DontNullTerminate: Bool) ?*Value;
89extern fn LLVMConstStringInContext(C: *Context, Str: [*]const u8, Length: c_uint, DontNullTerminate: Bool) ?*Value;
9090
9191pub const ConstInt = LLVMConstInt;
9292extern fn LLVMConstInt(IntTy: *Type, N: c_ulonglong, SignExtend: Bool) ?*Value;
src-self-hosted/main.zig+49-65
......@@ -126,7 +126,8 @@ pub fn main() !void {
126126
127127 try stderr.print("unknown command: {}\n\n", args[1]);
128128 try stderr.write(usage);
129 process.exit(1);
129 process.argsFree(allocator, args);
130 defer process.exit(1);
130131}
131132
132133const usage_build_generic =
......@@ -461,13 +462,12 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co
461462 comp.link_objects = link_objects;
462463
463464 comp.start();
464 const frame = async processBuildEvents(comp, color);
465 processBuildEvents(comp, color);
465466}
466467
467async fn processBuildEvents(comp: *Compilation, color: errmsg.Color) void {
468fn processBuildEvents(comp: *Compilation, color: errmsg.Color) void {
468469 var count: usize = 0;
469 while (true) {
470 // TODO directly awaiting async should guarantee memory allocation elision
470 while (true) { // TODO(Vexu)
471471 const build_event = comp.events.get();
472472 count += 1;
473473
......@@ -567,10 +567,6 @@ fn cmdLibC(allocator: *Allocator, args: []const []const u8) !void {
567567 var zig_compiler = try ZigCompiler.init(allocator);
568568 defer zig_compiler.deinit();
569569
570 const frame = async findLibCAsync(&zig_compiler);
571}
572
573async fn findLibCAsync(zig_compiler: *ZigCompiler) void {
574570 const libc = zig_compiler.getNativeLibC() catch |err| {
575571 stderr.print("unable to find libc: {}\n", @errorName(err)) catch process.exit(1);
576572 process.exit(1);
......@@ -644,11 +640,23 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {
644640 process.exit(1);
645641 }
646642
647 return asyncFmtMain(
648 allocator,
649 &flags,
650 color,
651 );
643 var fmt = Fmt{
644 .allocator = allocator,
645 .seen = event.Locked(Fmt.SeenMap).init(Fmt.SeenMap.init(allocator)),
646 .any_error = false,
647 .color = color,
648 };
649
650 const check_mode = flags.present("check");
651
652 var group = event.Group(FmtError!void).init(allocator);
653 for (flags.positionals.toSliceConst()) |file_path| {
654 try group.call(fmtPath, &fmt, file_path, check_mode);
655 }
656 try group.wait();
657 if (fmt.any_error) {
658 process.exit(1);
659 }
652660}
653661
654662const FmtError = error{
......@@ -673,30 +681,6 @@ const FmtError = error{
673681 CurrentWorkingDirectoryUnlinked,
674682} || fs.File.OpenError;
675683
676async fn asyncFmtMain(
677 allocator: *Allocator,
678 flags: *const Args,
679 color: errmsg.Color,
680) FmtError!void {
681 var fmt = Fmt{
682 .allocator = allocator,
683 .seen = event.Locked(Fmt.SeenMap).init(Fmt.SeenMap.init(allocator)),
684 .any_error = false,
685 .color = color,
686 };
687
688 const check_mode = flags.present("check");
689
690 var group = event.Group(FmtError!void).init(allocator);
691 for (flags.positionals.toSliceConst()) |file_path| {
692 try group.call(fmtPath, &fmt, file_path, check_mode);
693 }
694 try group.wait();
695 if (fmt.any_error) {
696 process.exit(1);
697 }
698}
699
700684async fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtError!void {
701685 const file_path = try std.mem.dupe(fmt.allocator, u8, file_path_ref);
702686 defer fmt.allocator.free(file_path);
......@@ -708,33 +692,33 @@ async fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtErro
708692 if (try held.value.put(file_path, {})) |_| return;
709693 }
710694
711 const source_code = "";
712 // const source_code = event.fs.readFile(
713 // file_path,
714 // max_src_size,
715 // ) catch |err| switch (err) {
716 // error.IsDir, error.AccessDenied => {
717 // // TODO make event based (and dir.next())
718 // var dir = try fs.Dir.cwd().openDirList(file_path);
719 // defer dir.close();
720
721 // var group = event.Group(FmtError!void).init(fmt.allocator);
722 // while (try dir.next()) |entry| {
723 // if (entry.kind == fs.Dir.Entry.Kind.Directory or mem.endsWith(u8, entry.name, ".zig")) {
724 // const full_path = try fs.path.join(fmt.allocator, [_][]const u8{ file_path, entry.name });
725 // try group.call(fmtPath, fmt, full_path, check_mode);
726 // }
727 // }
728 // return group.wait();
729 // },
730 // else => {
731 // // TODO lock stderr printing
732 // try stderr.print("unable to open '{}': {}\n", file_path, err);
733 // fmt.any_error = true;
734 // return;
735 // },
736 // };
737 // defer fmt.allocator.free(source_code);
695 const source_code = event.fs.readFile(
696 fmt.allocator,
697 file_path,
698 max_src_size,
699 ) catch |err| switch (err) {
700 error.IsDir, error.AccessDenied => {
701 var dir = try fs.Dir.cwd().openDirList(file_path);
702 defer dir.close();
703
704 var group = event.Group(FmtError!void).init(fmt.allocator);
705 var it = dir.iterate();
706 while (try it.next()) |entry| {
707 if (entry.kind == .Directory or mem.endsWith(u8, entry.name, ".zig")) {
708 const full_path = try fs.path.join(fmt.allocator, [_][]const u8{ file_path, entry.name });
709 try group.call(fmtPath, fmt, full_path, check_mode);
710 }
711 }
712 return group.wait();
713 },
714 else => {
715 // TODO lock stderr printing
716 try stderr.print("unable to open '{}': {}\n", file_path, err);
717 fmt.any_error = true;
718 return;
719 },
720 };
721 defer fmt.allocator.free(source_code);
738722
739723 const tree = std.zig.parse(fmt.allocator, source_code) catch |err| {
740724 try stderr.print("error parsing file '{}': {}\n", file_path, err);
src-self-hosted/test.zig+4-7
......@@ -116,7 +116,7 @@ pub const TestContext = struct {
116116 const file_index = try std.fmt.bufPrint(file_index_buf[0..], "{}", self.file_index.incr());
117117 const file1_path = try std.fs.path.join(allocator, [_][]const u8{ tmp_dir_name, file_index, file1 });
118118
119 const output_file = try std.fmt.allocPrint(allocator, "{}-out{}", file1_path, (Target{.Native = {}}).exeFileExt());
119 const output_file = try std.fmt.allocPrint(allocator, "{}-out{}", file1_path, (Target{ .Native = {} }).exeFileExt());
120120 if (std.fs.path.dirname(file1_path)) |dirname| {
121121 try std.fs.makePath(allocator, dirname);
122122 }
......@@ -148,15 +148,12 @@ pub const TestContext = struct {
148148 exe_file: []const u8,
149149 expected_output: []const u8,
150150 ) anyerror!void {
151 // TODO this should not be necessary
152 const exe_file_2 = try std.mem.dupe(allocator, u8, exe_file);
153
154151 defer comp.destroy();
155152 const build_event = comp.events.get();
156153
157154 switch (build_event) {
158155 .Ok => {
159 const argv = [_][]const u8{exe_file_2};
156 const argv = [_][]const u8{exe_file};
160157 // TODO use event loop
161158 const child = try std.ChildProcess.exec(allocator, argv, null, null, 1024 * 1024);
162159 switch (child.term) {
......@@ -173,8 +170,8 @@ pub const TestContext = struct {
173170 return error.OutputMismatch;
174171 }
175172 },
176 Compilation.Event.Error => |err| return err,
177 Compilation.Event.Fail => |msgs| {
173 .Error => |err| return err,
174 .Fail => |msgs| {
178175 const stderr = std.io.getStdErr();
179176 try stderr.write("build incorrectly failed:\n");
180177 for (msgs) |msg| {
src-self-hosted/type.zig+11-11
......@@ -53,7 +53,7 @@ pub const Type = struct {
5353 base: *Type,
5454 allocator: *Allocator,
5555 llvm_context: *llvm.Context,
56 ) (error{OutOfMemory}!*llvm.Type) {
56 ) error{OutOfMemory}!*llvm.Type {
5757 switch (base.id) {
5858 .Struct => return @fieldParentPtr(Struct, "base", base).getLlvmType(allocator, llvm_context),
5959 .Fn => return @fieldParentPtr(Fn, "base", base).getLlvmType(allocator, llvm_context),
......@@ -184,7 +184,7 @@ pub const Type = struct {
184184
185185 /// If you happen to have an llvm context handy, use getAbiAlignmentInContext instead.
186186 /// Otherwise, this one will grab one from the pool and then release it.
187 pub async fn getAbiAlignment(base: *Type, comp: *Compilation) !u32 {
187 pub fn getAbiAlignment(base: *Type, comp: *Compilation) !u32 {
188188 if (base.abi_alignment.start()) |ptr| return ptr.*;
189189
190190 {
......@@ -200,7 +200,7 @@ pub const Type = struct {
200200 }
201201
202202 /// If you have an llvm conext handy, you can use it here.
203 pub async fn getAbiAlignmentInContext(base: *Type, comp: *Compilation, llvm_context: *llvm.Context) !u32 {
203 pub fn getAbiAlignmentInContext(base: *Type, comp: *Compilation, llvm_context: *llvm.Context) !u32 {
204204 if (base.abi_alignment.start()) |ptr| return ptr.*;
205205
206206 base.abi_alignment.data = base.resolveAbiAlignment(comp, llvm_context);
......@@ -209,7 +209,7 @@ pub const Type = struct {
209209 }
210210
211211 /// Lower level function that does the work. See getAbiAlignment.
212 async fn resolveAbiAlignment(base: *Type, comp: *Compilation, llvm_context: *llvm.Context) !u32 {
212 fn resolveAbiAlignment(base: *Type, comp: *Compilation, llvm_context: *llvm.Context) !u32 {
213213 const llvm_type = try base.getLlvmType(comp.gpa(), llvm_context);
214214 return @intCast(u32, llvm.ABIAlignmentOfType(comp.target_data_ref, llvm_type));
215215 }
......@@ -367,7 +367,7 @@ pub const Type = struct {
367367 }
368368
369369 /// takes ownership of key.Normal.params on success
370 pub async fn get(comp: *Compilation, key: Key) !*Fn {
370 pub fn get(comp: *Compilation, key: Key) !*Fn {
371371 {
372372 const held = comp.fn_type_table.acquire();
373373 defer held.release();
......@@ -564,7 +564,7 @@ pub const Type = struct {
564564 return comp.u8_type;
565565 }
566566
567 pub async fn get(comp: *Compilation, key: Key) !*Int {
567 pub fn get(comp: *Compilation, key: Key) !*Int {
568568 {
569569 const held = comp.int_type_table.acquire();
570570 defer held.release();
......@@ -606,7 +606,7 @@ pub const Type = struct {
606606 comp.registerGarbage(Int, &self.garbage_node);
607607 }
608608
609 pub async fn gcDestroy(self: *Int, comp: *Compilation) void {
609 pub fn gcDestroy(self: *Int, comp: *Compilation) void {
610610 {
611611 const held = comp.int_type_table.acquire();
612612 defer held.release();
......@@ -700,7 +700,7 @@ pub const Type = struct {
700700 comp.registerGarbage(Pointer, &self.garbage_node);
701701 }
702702
703 pub async fn gcDestroy(self: *Pointer, comp: *Compilation) void {
703 pub fn gcDestroy(self: *Pointer, comp: *Compilation) void {
704704 {
705705 const held = comp.ptr_type_table.acquire();
706706 defer held.release();
......@@ -711,14 +711,14 @@ pub const Type = struct {
711711 comp.gpa().destroy(self);
712712 }
713713
714 pub async fn getAlignAsInt(self: *Pointer, comp: *Compilation) u32 {
714 pub fn getAlignAsInt(self: *Pointer, comp: *Compilation) u32 {
715715 switch (self.key.alignment) {
716716 .Abi => return self.key.child_type.getAbiAlignment(comp),
717717 .Override => |alignment| return alignment,
718718 }
719719 }
720720
721 pub async fn get(
721 pub fn get(
722722 comp: *Compilation,
723723 key: Key,
724724 ) !*Pointer {
......@@ -828,7 +828,7 @@ pub const Type = struct {
828828 comp.gpa().destroy(self);
829829 }
830830
831 pub async fn get(comp: *Compilation, key: Key) !*Array {
831 pub fn get(comp: *Compilation, key: Key) !*Array {
832832 key.elem_type.base.ref();
833833 errdefer key.elem_type.base.deref(comp);
834834
src-self-hosted/util.zig+12-11
......@@ -32,21 +32,21 @@ pub fn getFloatAbi(self: Target) FloatAbi {
3232 };
3333}
3434
35pub fn getObjectFormat(self: Target) Target.ObjectFormat {
36 return switch (self) {
37 .Native => @import("builtin").object_format,
38 .Cross => {
35pub fn getObjectFormat(target: Target) Target.ObjectFormat {
36 switch (target) {
37 .Native => return @import("builtin").object_format,
38 .Cross => blk: {
3939 if (target.isWindows() or target.isUefi()) {
40 break .coff;
40 return .coff;
4141 } else if (target.isDarwin()) {
42 break .macho;
42 return .macho;
4343 }
4444 if (target.isWasm()) {
45 break .wasm;
45 return .wasm;
4646 }
47 break .elf;
47 return .elf;
4848 },
49 };
49 }
5050}
5151
5252pub fn getDynamicLinkerPath(self: Target) ?[]const u8 {
......@@ -156,7 +156,7 @@ pub fn getDynamicLinkerPath(self: Target) ?[]const u8 {
156156 }
157157}
158158
159pub fn getDarwinArchString(self: Target) []const u8 {
159pub fn getDarwinArchString(self: Target) [:0]const u8 {
160160 const arch = self.getArch();
161161 switch (arch) {
162162 .aarch64 => return "arm64",
......@@ -166,7 +166,8 @@ pub fn getDarwinArchString(self: Target) []const u8 {
166166 .powerpc => return "ppc",
167167 .powerpc64 => return "ppc64",
168168 .powerpc64le => return "ppc64le",
169 else => return @tagName(arch),
169 // @tagName should be able to return sentinel terminated slice
170 else => @panic("TODO"), //return @tagName(arch),
170171 }
171172}
172173
src-self-hosted/value.zig+6-6
......@@ -156,7 +156,7 @@ pub const Value = struct {
156156 const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context);
157157 const llvm_fn = llvm.AddFunction(
158158 ofile.module,
159 self.symbol_name.ptr(),
159 self.symbol_name.toSliceConst(),
160160 llvm_fn_type,
161161 ) orelse return error.OutOfMemory;
162162
......@@ -241,7 +241,7 @@ pub const Value = struct {
241241 const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context);
242242 const llvm_fn = llvm.AddFunction(
243243 ofile.module,
244 self.symbol_name.ptr(),
244 self.symbol_name.toSliceConst(),
245245 llvm_fn_type,
246246 ) orelse return error.OutOfMemory;
247247
......@@ -334,7 +334,7 @@ pub const Value = struct {
334334 field_index: usize,
335335 };
336336
337 pub async fn createArrayElemPtr(
337 pub fn createArrayElemPtr(
338338 comp: *Compilation,
339339 array_val: *Array,
340340 mut: Type.Pointer.Mut,
......@@ -390,13 +390,13 @@ pub const Value = struct {
390390 const array_llvm_value = (try base_array.val.getLlvmConst(ofile)).?;
391391 const ptr_bit_count = ofile.comp.target_ptr_bits;
392392 const usize_llvm_type = llvm.IntTypeInContext(ofile.context, ptr_bit_count) orelse return error.OutOfMemory;
393 const indices = [_]*llvm.Value{
393 var indices = [_]*llvm.Value{
394394 llvm.ConstNull(usize_llvm_type) orelse return error.OutOfMemory,
395395 llvm.ConstInt(usize_llvm_type, base_array.elem_index, 0) orelse return error.OutOfMemory,
396396 };
397397 return llvm.ConstInBoundsGEP(
398398 array_llvm_value,
399 &indices,
399 @ptrCast([*]*llvm.Value, &indices),
400400 @intCast(c_uint, indices.len),
401401 ) orelse return error.OutOfMemory;
402402 },
......@@ -423,7 +423,7 @@ pub const Value = struct {
423423 };
424424
425425 /// Takes ownership of buffer
426 pub async fn createOwnedBuffer(comp: *Compilation, buffer: []u8) !*Array {
426 pub fn createOwnedBuffer(comp: *Compilation, buffer: []u8) !*Array {
427427 const u8_type = Type.Int.get_u8(comp);
428428 defer u8_type.base.base.deref(comp);
429429