Merge pull request #9219 from ziglang/unreachable-code

move "unreachable code" error from stage1 to stage2
This commit is contained in:
Andrew Kelley 2021-07-02 21:11:45 -04:00 committed by GitHub
commit bb98620c10
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 2732 additions and 2138 deletions

View File

@ -40,7 +40,7 @@ pub fn build(b: *Builder) !void {
var test_stage2 = b.addTest("src/test.zig");
test_stage2.setBuildMode(mode);
test_stage2.addPackagePath("stage2_tests", "test/stage2/test.zig");
test_stage2.addPackagePath("test_cases", "test/cases.zig");
const fmt_build_zig = b.addFmt(&[_][]const u8{"build.zig"});
@ -113,11 +113,15 @@ pub fn build(b: *Builder) !void {
if (is_stage1) {
exe.addIncludeDir("src");
exe.addIncludeDir("deps/SoftFloat-3e/source/include");
test_stage2.addIncludeDir("src");
test_stage2.addIncludeDir("deps/SoftFloat-3e/source/include");
// This is intentionally a dummy path. stage1.zig tries to @import("compiler_rt") in case
// of being built by cmake. But when built by zig it's gonna get a compiler_rt so that
// is pointless.
exe.addPackagePath("compiler_rt", "src/empty.zig");
exe.defineCMacro("ZIG_LINK_MODE", "Static");
test_stage2.defineCMacro("ZIG_LINK_MODE", "Static");
const softfloat = b.addStaticLibrary("softfloat", null);
softfloat.setBuildMode(.ReleaseFast);
@ -126,10 +130,15 @@ pub fn build(b: *Builder) !void {
softfloat.addIncludeDir("deps/SoftFloat-3e/source/8086");
softfloat.addIncludeDir("deps/SoftFloat-3e/source/include");
softfloat.addCSourceFiles(&softfloat_sources, &[_][]const u8{ "-std=c99", "-O3" });
exe.linkLibrary(softfloat);
test_stage2.linkLibrary(softfloat);
exe.addCSourceFiles(&stage1_sources, &exe_cflags);
exe.addCSourceFiles(&optimized_c_sources, &[_][]const u8{ "-std=c99", "-O3" });
test_stage2.addCSourceFiles(&stage1_sources, &exe_cflags);
test_stage2.addCSourceFiles(&optimized_c_sources, &[_][]const u8{ "-std=c99", "-O3" });
}
if (cmake_cfg) |cfg| {
// Inside this code path, we have to coordinate with system packaged LLVM, Clang, and LLD.
@ -139,8 +148,8 @@ pub fn build(b: *Builder) !void {
b.addSearchPrefix(cfg.cmake_prefix_path);
}
try addCmakeCfgOptionsToExe(b, cfg, tracy, exe);
try addCmakeCfgOptionsToExe(b, cfg, tracy, test_stage2);
try addCmakeCfgOptionsToExe(b, cfg, exe);
try addCmakeCfgOptionsToExe(b, cfg, test_stage2);
} else {
// Here we are -Denable-llvm but no cmake integration.
try addStaticLlvmOptionsToExe(exe);
@ -233,7 +242,9 @@ pub fn build(b: *Builder) !void {
const is_darling_enabled = b.option(bool, "enable-darling", "[Experimental] Use Darling to run cross compiled macOS tests") orelse false;
const glibc_multi_dir = b.option([]const u8, "enable-foreign-glibc", "Provide directory with glibc installations to run cross compiled tests that link glibc");
test_stage2.addBuildOption(bool, "enable_logging", enable_logging);
test_stage2.addBuildOption(bool, "skip_non_native", skip_non_native);
test_stage2.addBuildOption(bool, "skip_compile_errors", skip_compile_errors);
test_stage2.addBuildOption(bool, "is_stage1", is_stage1);
test_stage2.addBuildOption(bool, "omit_stage2", omit_stage2);
test_stage2.addBuildOption(bool, "have_llvm", enable_llvm);
@ -243,7 +254,8 @@ pub fn build(b: *Builder) !void {
test_stage2.addBuildOption(u32, "mem_leak_frames", mem_leak_frames * 2);
test_stage2.addBuildOption(bool, "enable_darling", is_darling_enabled);
test_stage2.addBuildOption(?[]const u8, "glibc_multi_install_dir", glibc_multi_dir);
test_stage2.addBuildOption([]const u8, "version", version);
test_stage2.addBuildOption([:0]const u8, "version", try b.allocator.dupeZ(u8, version));
test_stage2.addBuildOption(std.SemanticVersion, "semver", semver);
const test_stage2_step = b.step("test-stage2", "Run the stage2 compiler tests");
test_stage2_step.dependOn(&test_stage2.step);
@ -339,9 +351,6 @@ pub fn build(b: *Builder) !void {
}
// tests for this feature are disabled until we have the self-hosted compiler available
// toolchain_step.dependOn(tests.addGenHTests(b, test_filter));
if (!skip_compile_errors) {
toolchain_step.dependOn(tests.addCompileErrorTests(b, test_filter, modes));
}
const std_step = tests.addPkgTests(
b,
@ -383,7 +392,6 @@ const exe_cflags = [_][]const u8{
fn addCmakeCfgOptionsToExe(
b: *Builder,
cfg: CMakeConfig,
tracy: ?[]const u8,
exe: *std.build.LibExeObjStep,
) !void {
exe.addObjectFile(fs.path.join(b.allocator, &[_][]const u8{
@ -397,7 +405,7 @@ fn addCmakeCfgOptionsToExe(
addCMakeLibraryList(exe, cfg.lld_libraries);
addCMakeLibraryList(exe, cfg.llvm_libraries);
const need_cpp_includes = tracy != null;
const need_cpp_includes = true;
// System -lc++ must be used because in this code path we are attempting to link
// against system-provided LLVM, Clang, LLD.
@ -486,9 +494,9 @@ fn addCxxKnownPath(
if (need_cpp_includes) {
// I used these temporarily for testing something but we obviously need a
// more general purpose solution here.
//exe.addIncludeDir("/nix/store/b3zsk4ihlpiimv3vff86bb5bxghgdzb9-gcc-9.2.0/lib/gcc/x86_64-unknown-linux-gnu/9.2.0/../../../../include/c++/9.2.0");
//exe.addIncludeDir("/nix/store/b3zsk4ihlpiimv3vff86bb5bxghgdzb9-gcc-9.2.0/lib/gcc/x86_64-unknown-linux-gnu/9.2.0/../../../../include/c++/9.2.0/x86_64-unknown-linux-gnu");
//exe.addIncludeDir("/nix/store/b3zsk4ihlpiimv3vff86bb5bxghgdzb9-gcc-9.2.0/lib/gcc/x86_64-unknown-linux-gnu/9.2.0/../../../../include/c++/9.2.0/backward");
//exe.addIncludeDir("/nix/store/fvf3qjqa5qpcjjkq37pb6ypnk1mzhf5h-gcc-9.3.0/lib/gcc/x86_64-unknown-linux-gnu/9.3.0/../../../../include/c++/9.3.0");
//exe.addIncludeDir("/nix/store/fvf3qjqa5qpcjjkq37pb6ypnk1mzhf5h-gcc-9.3.0/lib/gcc/x86_64-unknown-linux-gnu/9.3.0/../../../../include/c++/9.3.0/x86_64-unknown-linux-gnu");
//exe.addIncludeDir("/nix/store/fvf3qjqa5qpcjjkq37pb6ypnk1mzhf5h-gcc-9.3.0/lib/gcc/x86_64-unknown-linux-gnu/9.3.0/../../../../include/c++/9.3.0/backward");
}
}

View File

@ -8,6 +8,7 @@ const Progress = std.Progress;
const print = std.debug.print;
const mem = std.mem;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const max_doc_file_size = 10 * 1024 * 1024;
@ -326,7 +327,7 @@ const Action = enum {
Close,
};
fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
fn genToc(allocator: *Allocator, tokenizer: *Tokenizer) !Toc {
var urls = std.StringHashMap(Token).init(allocator);
errdefer urls.deinit();
@ -630,7 +631,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
};
}
fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {
fn urlize(allocator: *Allocator, input: []const u8) ![]u8 {
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();
@ -649,7 +650,7 @@ fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {
return buf.toOwnedSlice();
}
fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {
fn escapeHtml(allocator: *Allocator, input: []const u8) ![]u8 {
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();
@ -695,7 +696,7 @@ test "term color" {
testing.expectEqualSlices(u8, "A<span class=\"t32\">green</span>B", result);
}
fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {
fn termColor(allocator: *Allocator, input: []const u8) ![]u8 {
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();
@ -789,8 +790,15 @@ fn isType(name: []const u8) bool {
return false;
}
fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: anytype, source_token: Token, raw_src: []const u8) !void {
const src = mem.trim(u8, raw_src, " \n");
fn tokenizeAndPrintRaw(
allocator: *Allocator,
docgen_tokenizer: *Tokenizer,
out: anytype,
source_token: Token,
raw_src: []const u8,
) !void {
const src_non_terminated = mem.trim(u8, raw_src, " \n");
const src = try allocator.dupeZ(u8, src_non_terminated);
try out.writeAll("<code class=\"zig\">");
var tokenizer = std.zig.Tokenizer.init(src);
var index: usize = 0;
@ -1016,12 +1024,24 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: anytype, source_token:
try out.writeAll("</code>");
}
fn tokenizeAndPrint(docgen_tokenizer: *Tokenizer, out: anytype, source_token: Token) !void {
fn tokenizeAndPrint(
allocator: *Allocator,
docgen_tokenizer: *Tokenizer,
out: anytype,
source_token: Token,
) !void {
const raw_src = docgen_tokenizer.buffer[source_token.start..source_token.end];
return tokenizeAndPrintRaw(docgen_tokenizer, out, source_token, raw_src);
return tokenizeAndPrintRaw(allocator, docgen_tokenizer, out, source_token, raw_src);
}
fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: anytype, zig_exe: []const u8, do_code_tests: bool) !void {
fn genHtml(
allocator: *Allocator,
tokenizer: *Tokenizer,
toc: *Toc,
out: anytype,
zig_exe: []const u8,
do_code_tests: bool,
) !void {
var progress = Progress{};
const root_node = try progress.start("Generating docgen examples", toc.nodes.len);
defer root_node.end();
@ -1048,7 +1068,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
},
.Builtin => |tok| {
try out.writeAll("<pre>");
try tokenizeAndPrintRaw(tokenizer, out, tok, builtin_code);
try tokenizeAndPrintRaw(allocator, tokenizer, out, tok, builtin_code);
try out.writeAll("</pre>");
},
.HeaderOpen => |info| {
@ -1069,7 +1089,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
try out.writeAll("</ul>\n");
},
.Syntax => |content_tok| {
try tokenizeAndPrint(tokenizer, out, content_tok);
try tokenizeAndPrint(allocator, tokenizer, out, content_tok);
},
.Code => |code| {
const raw_source = tokenizer.buffer[code.source_token.start..code.source_token.end];
@ -1078,7 +1098,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
try out.print("<p class=\"file\">{s}.zig</p>", .{code.name});
}
try out.writeAll("<pre>");
try tokenizeAndPrint(tokenizer, out, code.source_token);
try tokenizeAndPrint(allocator, tokenizer, out, code.source_token);
try out.writeAll("</pre>");
if (!do_code_tests) {
@ -1497,7 +1517,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any
}
}
fn exec(allocator: *mem.Allocator, env_map: *std.BufMap, args: []const []const u8) !ChildProcess.ExecResult {
fn exec(allocator: *Allocator, env_map: *std.BufMap, args: []const []const u8) !ChildProcess.ExecResult {
const result = try ChildProcess.exec(.{
.allocator = allocator,
.argv = args,
@ -1521,7 +1541,7 @@ fn exec(allocator: *mem.Allocator, env_map: *std.BufMap, args: []const []const u
return result;
}
fn getBuiltinCode(allocator: *mem.Allocator, env_map: *std.BufMap, zig_exe: []const u8) ![]const u8 {
fn getBuiltinCode(allocator: *Allocator, env_map: *std.BufMap, zig_exe: []const u8) ![]const u8 {
const result = try exec(allocator, env_map, &[_][]const u8{ zig_exe, "build-obj", "--show-builtin" });
return result.stdout;
}

View File

@ -3025,7 +3025,7 @@ test "@tagName" {
</p>
{#code_begin|obj_err|parameter of type 'Foo' not allowed in function with calling convention 'C'#}
const Foo = enum { a, b, c };
export fn entry(foo: Foo) void { }
export fn entry(foo: Foo) void { _ = foo; }
{#code_end#}
<p>
For a C-ABI-compatible enum, provide an explicit tag type to
@ -3346,7 +3346,7 @@ test "call foo" {
<p>
Blocks are used to limit the scope of variable declarations:
</p>
{#code_begin|test_err|undeclared identifier#}
{#code_begin|test_err|unused local variable#}
test "access variable after block scope" {
{
var x: i32 = 1;
@ -3377,7 +3377,7 @@ test "labeled break from labeled block expression" {
{#header_open|Shadowing#}
<p>It is never allowed for an identifier to "hide" another one by using the same name:</p>
{#code_begin|test_err|redefinition#}
{#code_begin|test_err|local shadows declaration#}
const pi = 3.14;
test "inside test block" {
@ -4228,8 +4228,8 @@ test "type of unreachable" {
comptime {
// The type of unreachable is noreturn.
// However this assertion will still fail because
// evaluating unreachable at compile-time is a compile error.
// However this assertion will still fail to compile because
// unreachable expressions are compile errors.
assert(@TypeOf(unreachable) == noreturn);
}
@ -5257,6 +5257,7 @@ test "float widening" {
// Compile time coercion of float to int
test "implicit cast to comptime_int" {
var f: f32 = 54.0 / 5;
_ = f;
}
{#code_end#}
{#header_close#}
@ -5817,6 +5818,7 @@ fn foo(condition: bool) void {
if (condition) f32 else u64,
1234,
5678);
_ = result;
}
{#code_end#}
<p>
@ -6313,7 +6315,7 @@ pub fn printValue(self: *Writer, value: anytype) !void {
<p>
And now, what happens if we give too many arguments to {#syntax#}printf{#endsyntax#}?
</p>
{#code_begin|test_err|Unused argument in "here is a string: '{s}' here is a number: {}#}
{#code_begin|test_err|Unused argument in 'here is a string: '{s}' here is a number: {}#}
const print = @import("std").debug.print;
const a_number: i32 = 1234;
@ -8853,6 +8855,7 @@ pub fn main() void {
comptime {
const array: [5]u8 = "hello".*;
const garbage = array[5];
_ = garbage;
}
{#code_end#}
<p>At runtime:</p>
@ -8873,6 +8876,7 @@ fn foo(x: []const u8) u8 {
comptime {
const value: i32 = -1;
const unsigned = @intCast(u32, value);
_ = unsigned;
}
{#code_end#}
<p>At runtime:</p>
@ -8895,6 +8899,7 @@ pub fn main() void {
comptime {
const spartan_count: u16 = 300;
const byte = @intCast(u8, spartan_count);
_ = byte;
}
{#code_end#}
<p>At runtime:</p>
@ -9028,6 +9033,7 @@ test "wraparound addition and subtraction" {
{#code_begin|test_err|operation caused overflow#}
comptime {
const x = @shlExact(@as(u8, 0b01010101), 2);
_ = x;
}
{#code_end#}
<p>At runtime:</p>
@ -9046,6 +9052,7 @@ pub fn main() void {
{#code_begin|test_err|exact shift shifted out 1 bits#}
comptime {
const x = @shrExact(@as(u8, 0b10101010), 2);
_ = x;
}
{#code_end#}
<p>At runtime:</p>
@ -9066,6 +9073,7 @@ comptime {
const a: i32 = 1;
const b: i32 = 0;
const c = a / b;
_ = c;
}
{#code_end#}
<p>At runtime:</p>
@ -9087,6 +9095,7 @@ comptime {
const a: i32 = 10;
const b: i32 = 0;
const c = a % b;
_ = c;
}
{#code_end#}
<p>At runtime:</p>
@ -9108,6 +9117,7 @@ comptime {
const a: u32 = 10;
const b: u32 = 3;
const c = @divExact(a, b);
_ = c;
}
{#code_end#}
<p>At runtime:</p>
@ -9300,6 +9310,7 @@ fn foo(set1: Set1) void {
comptime {
const ptr = @intToPtr(*align(1) i32, 0x1);
const aligned = @alignCast(4, ptr);
_ = aligned;
}
{#code_end#}
<p>At runtime:</p>
@ -9414,6 +9425,7 @@ fn bar(f: *Foo) void {
comptime {
const opt_ptr: ?*i32 = null;
const ptr = @ptrCast(*i32, opt_ptr);
_ = ptr;
}
{#code_end#}
<p>At runtime:</p>

View File

@ -362,8 +362,8 @@ pub fn format(
const missing_count = arg_state.args_len - @popCount(ArgSetType, arg_state.used_args);
switch (missing_count) {
0 => unreachable,
1 => @compileError("Unused argument in \"" ++ fmt ++ "\""),
else => @compileError((comptime comptimePrint("{d}", .{missing_count})) ++ " unused arguments in \"" ++ fmt ++ "\""),
1 => @compileError("Unused argument in '" ++ fmt ++ "'"),
else => @compileError((comptime comptimePrint("{d}", .{missing_count})) ++ " unused arguments in '" ++ fmt ++ "'"),
}
}
}

View File

@ -2297,14 +2297,14 @@ pub fn replaceOwned(comptime T: type, allocator: *Allocator, input: []const T, n
}
test "replaceOwned" {
const allocator = std.heap.page_allocator;
const gpa = std.testing.allocator;
const base_replace = replaceOwned(u8, allocator, "All your base are belong to us", "base", "Zig") catch unreachable;
defer allocator.free(base_replace);
const base_replace = replaceOwned(u8, gpa, "All your base are belong to us", "base", "Zig") catch @panic("out of memory");
defer gpa.free(base_replace);
try testing.expect(eql(u8, base_replace, "All your Zig are belong to us"));
const zen_replace = replaceOwned(u8, allocator, "Favor reading code over writing code.", " code", "") catch unreachable;
defer allocator.free(zen_replace);
const zen_replace = replaceOwned(u8, gpa, "Favor reading code over writing code.", " code", "") catch @panic("out of memory");
defer gpa.free(zen_replace);
try testing.expect(eql(u8, zen_replace, "Favor reading over writing."));
}

View File

@ -57,13 +57,13 @@ pub const SimpleNetworkProtocol = extern struct {
}
/// Modifies or resets the current station address, if supported.
pub fn stationAddress(self: *const SimpleNetworkProtocol, reset: bool, new: ?*const MacAddress) Status {
return self._station_address(self, reset, new);
pub fn stationAddress(self: *const SimpleNetworkProtocol, reset_flag: bool, new: ?*const MacAddress) Status {
return self._station_address(self, reset_flag, new);
}
/// Resets or collects the statistics on a network interface.
pub fn statistics(self: *const SimpleNetworkProtocol, reset_: bool, statistics_size: ?*usize, statistics_table: ?*NetworkStatistics) Status {
return self._statistics(self, reset_, statistics_size, statistics_table);
pub fn statistics(self: *const SimpleNetworkProtocol, reset_flag: bool, statistics_size: ?*usize, statistics_table: ?*NetworkStatistics) Status {
return self._statistics(self, reset_flag, statistics_size, statistics_table);
}
/// Converts a multicast IP address to a multicast HW MAC address.

View File

@ -247,7 +247,6 @@ pub const Utf8View = struct {
} else |err| switch (err) {
error.InvalidUtf8 => {
@compileError("invalid utf8");
unreachable;
},
}
}

View File

@ -6,6 +6,7 @@
const std = @import("std.zig");
const tokenizer = @import("zig/tokenizer.zig");
const fmt = @import("zig/fmt.zig");
const assert = std.debug.assert;
pub const Token = tokenizer.Token;
pub const Tokenizer = tokenizer.Tokenizer;
@ -183,29 +184,48 @@ pub fn binNameAlloc(allocator: *std.mem.Allocator, options: BinNameOptions) erro
}
}
pub const ParsedCharLiteral = union(enum) {
success: u32,
/// The character after backslash is not recognized.
invalid_escape_character: usize,
/// Expected hex digit at this index.
expected_hex_digit: usize,
/// Unicode escape sequence had no digits with rbrace at this index.
empty_unicode_escape_sequence: usize,
/// Expected hex digit or '}' at this index.
expected_hex_digit_or_rbrace: usize,
/// The unicode point is outside the range of Unicode codepoints.
unicode_escape_overflow: usize,
/// Expected '{' at this index.
expected_lbrace: usize,
/// Expected the terminating single quote at this index.
expected_end: usize,
/// The character at this index cannot be represented without an escape sequence.
invalid_character: usize,
};
/// Only validates escape sequence characters.
/// Slice must be valid utf8 starting and ending with "'" and exactly one codepoint in between.
pub fn parseCharLiteral(
slice: []const u8,
bad_index: *usize, // populated if error.InvalidCharacter is returned
) error{InvalidCharacter}!u32 {
std.debug.assert(slice.len >= 3 and slice[0] == '\'' and slice[slice.len - 1] == '\'');
pub fn parseCharLiteral(slice: []const u8) ParsedCharLiteral {
assert(slice.len >= 3 and slice[0] == '\'' and slice[slice.len - 1] == '\'');
if (slice[1] == '\\') {
switch (slice[2]) {
'n' => return '\n',
'r' => return '\r',
'\\' => return '\\',
't' => return '\t',
'\'' => return '\'',
'"' => return '"',
switch (slice[1]) {
0 => return .{ .invalid_character = 1 },
'\\' => switch (slice[2]) {
'n' => return .{ .success = '\n' },
'r' => return .{ .success = '\r' },
'\\' => return .{ .success = '\\' },
't' => return .{ .success = '\t' },
'\'' => return .{ .success = '\'' },
'"' => return .{ .success = '"' },
'x' => {
if (slice.len != 6) {
bad_index.* = slice.len - 2;
return error.InvalidCharacter;
if (slice.len < 4) {
return .{ .expected_hex_digit = 3 };
}
var value: u32 = 0;
for (slice[3..5]) |c, i| {
var i: usize = 3;
while (i < 5) : (i += 1) {
const c = slice[i];
switch (c) {
'0'...'9' => {
value *= 16;
@ -220,20 +240,28 @@ pub fn parseCharLiteral(
value += c - 'A' + 10;
},
else => {
bad_index.* = 3 + i;
return error.InvalidCharacter;
return .{ .expected_hex_digit = i };
},
}
}
return value;
if (slice[i] != '\'') {
return .{ .expected_end = i };
}
return .{ .success = value };
},
'u' => {
if (slice.len < "'\\u{0}'".len or slice[3] != '{' or slice[slice.len - 2] != '}') {
bad_index.* = 2;
return error.InvalidCharacter;
var i: usize = 3;
if (slice[i] != '{') {
return .{ .expected_lbrace = i };
}
i += 1;
if (slice[i] == '}') {
return .{ .empty_unicode_escape_sequence = i };
}
var value: u32 = 0;
for (slice[4 .. slice.len - 2]) |c, i| {
while (i < slice.len) : (i += 1) {
const c = slice[i];
switch (c) {
'0'...'9' => {
value *= 16;
@ -247,49 +275,112 @@ pub fn parseCharLiteral(
value *= 16;
value += c - 'A' + 10;
},
else => {
bad_index.* = 4 + i;
return error.InvalidCharacter;
'}' => {
i += 1;
break;
},
else => return .{ .expected_hex_digit_or_rbrace = i },
}
if (value > 0x10ffff) {
bad_index.* = 4 + i;
return error.InvalidCharacter;
return .{ .unicode_escape_overflow = i };
}
}
return value;
if (slice[i] != '\'') {
return .{ .expected_end = i };
}
return .{ .success = value };
},
else => {
bad_index.* = 2;
return error.InvalidCharacter;
},
}
else => return .{ .invalid_escape_character = 2 },
},
else => {
const codepoint = std.unicode.utf8Decode(slice[1 .. slice.len - 1]) catch unreachable;
return .{ .success = codepoint };
},
}
return std.unicode.utf8Decode(slice[1 .. slice.len - 1]) catch unreachable;
}
test "parseCharLiteral" {
var bad_index: usize = undefined;
try std.testing.expectEqual(try parseCharLiteral("'a'", &bad_index), 'a');
try std.testing.expectEqual(try parseCharLiteral("'ä'", &bad_index), 'ä');
try std.testing.expectEqual(try parseCharLiteral("'\\x00'", &bad_index), 0);
try std.testing.expectEqual(try parseCharLiteral("'\\x4f'", &bad_index), 0x4f);
try std.testing.expectEqual(try parseCharLiteral("'\\x4F'", &bad_index), 0x4f);
try std.testing.expectEqual(try parseCharLiteral("'ぁ'", &bad_index), 0x3041);
try std.testing.expectEqual(try parseCharLiteral("'\\u{0}'", &bad_index), 0);
try std.testing.expectEqual(try parseCharLiteral("'\\u{3041}'", &bad_index), 0x3041);
try std.testing.expectEqual(try parseCharLiteral("'\\u{7f}'", &bad_index), 0x7f);
try std.testing.expectEqual(try parseCharLiteral("'\\u{7FFF}'", &bad_index), 0x7FFF);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 'a' },
parseCharLiteral("'a'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 'ä' },
parseCharLiteral("'ä'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0 },
parseCharLiteral("'\\x00'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x4f },
parseCharLiteral("'\\x4f'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x4f },
parseCharLiteral("'\\x4F'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x3041 },
parseCharLiteral("'ぁ'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0 },
parseCharLiteral("'\\u{0}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x3041 },
parseCharLiteral("'\\u{3041}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x7f },
parseCharLiteral("'\\u{7f}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .success = 0x7fff },
parseCharLiteral("'\\u{7FFF}'"),
);
try std.testing.expectError(error.InvalidCharacter, parseCharLiteral("'\\x0'", &bad_index));
try std.testing.expectError(error.InvalidCharacter, parseCharLiteral("'\\x000'", &bad_index));
try std.testing.expectError(error.InvalidCharacter, parseCharLiteral("'\\y'", &bad_index));
try std.testing.expectError(error.InvalidCharacter, parseCharLiteral("'\\u'", &bad_index));
try std.testing.expectError(error.InvalidCharacter, parseCharLiteral("'\\uFFFF'", &bad_index));
try std.testing.expectError(error.InvalidCharacter, parseCharLiteral("'\\u{}'", &bad_index));
try std.testing.expectError(error.InvalidCharacter, parseCharLiteral("'\\u{FFFFFF}'", &bad_index));
try std.testing.expectError(error.InvalidCharacter, parseCharLiteral("'\\u{FFFF'", &bad_index));
try std.testing.expectError(error.InvalidCharacter, parseCharLiteral("'\\u{FFFF}x'", &bad_index));
try std.testing.expectEqual(
ParsedCharLiteral{ .expected_hex_digit = 4 },
parseCharLiteral("'\\x0'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .expected_end = 5 },
parseCharLiteral("'\\x000'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .invalid_escape_character = 2 },
parseCharLiteral("'\\y'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .expected_lbrace = 3 },
parseCharLiteral("'\\u'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .expected_lbrace = 3 },
parseCharLiteral("'\\uFFFF'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .empty_unicode_escape_sequence = 4 },
parseCharLiteral("'\\u{}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .unicode_escape_overflow = 9 },
parseCharLiteral("'\\u{FFFFFF}'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .expected_hex_digit_or_rbrace = 8 },
parseCharLiteral("'\\u{FFFF'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .expected_end = 9 },
parseCharLiteral("'\\u{FFFF}x'"),
);
try std.testing.expectEqual(
ParsedCharLiteral{ .invalid_character = 1 },
parseCharLiteral("'\x00'"),
);
}
test {

View File

@ -20,7 +20,7 @@ pub const NodeList = std.MultiArrayList(Node);
pub const Tree = struct {
/// Reference to externally-owned data.
source: []const u8,
source: [:0]const u8,
tokens: TokenList.Slice,
/// The root AST node is assumed to be index 0. Since there can be no
@ -135,6 +135,8 @@ pub const Tree = struct {
const token_tags = tree.tokens.items(.tag);
switch (parse_error.tag) {
.asterisk_after_ptr_deref => {
// Note that the token will point at the `.*` but ideally the source
// location would point to the `*` after the `.*`.
return stream.writeAll("'.*' cannot be followed by '*'. Are you missing a space?");
},
.decl_between_fields => {
@ -284,7 +286,7 @@ pub const Tree = struct {
return stream.writeAll("bit range not allowed on slices and arrays");
},
.invalid_token => {
return stream.print("invalid token '{s}'", .{
return stream.print("invalid token: '{s}'", .{
token_tags[parse_error.token].symbol(),
});
},

View File

@ -17,7 +17,7 @@ pub const Error = error{ParseError} || Allocator.Error;
/// Result should be freed with tree.deinit() when there are
/// no more references to any of the tokens or nodes.
pub fn parse(gpa: *Allocator, source: []const u8) Allocator.Error!Tree {
pub fn parse(gpa: *Allocator, source: [:0]const u8) Allocator.Error!Tree {
var tokens = ast.TokenList{};
defer tokens.deinit(gpa);

View File

@ -5194,7 +5194,7 @@ const maxInt = std.math.maxInt;
var fixed_buffer_mem: [100 * 1024]u8 = undefined;
fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *bool) ![]u8 {
fn testParse(source: [:0]const u8, allocator: *mem.Allocator, anything_changed: *bool) ![]u8 {
const stderr = io.getStdErr().writer();
var tree = try std.zig.parse(allocator, source);
@ -5222,7 +5222,7 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b
anything_changed.* = !mem.eql(u8, formatted, source);
return formatted;
}
fn testTransform(source: []const u8, expected_source: []const u8) !void {
fn testTransform(source: [:0]const u8, expected_source: []const u8) !void {
const needed_alloc_count = x: {
// Try it once with unlimited memory, make sure it works
var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
@ -5268,13 +5268,13 @@ fn testTransform(source: []const u8, expected_source: []const u8) !void {
}
}
}
fn testCanonical(source: []const u8) !void {
fn testCanonical(source: [:0]const u8) !void {
return testTransform(source, source);
}
const Error = std.zig.ast.Error.Tag;
fn testError(source: []const u8, expected_errors: []const Error) !void {
fn testError(source: [:0]const u8, expected_errors: []const Error) !void {
var tree = try std.zig.parse(std.testing.allocator, source);
defer tree.deinit(std.testing.allocator);

View File

@ -326,7 +326,7 @@ pub const Token = struct {
};
pub const Tokenizer = struct {
buffer: []const u8,
buffer: [:0]const u8,
index: usize,
pending_invalid_token: ?Token,
@ -335,7 +335,7 @@ pub const Tokenizer = struct {
std.debug.warn("{s} \"{s}\"\n", .{ @tagName(token.tag), self.buffer[token.start..token.end] });
}
pub fn init(buffer: []const u8) Tokenizer {
pub fn init(buffer: [:0]const u8) Tokenizer {
// Skip the UTF-8 BOM if present
const src_start = if (mem.startsWith(u8, buffer, "\xEF\xBB\xBF")) 3 else @as(usize, 0);
return Tokenizer{
@ -373,7 +373,6 @@ pub const Tokenizer = struct {
line_comment,
doc_comment_start,
doc_comment,
container_doc_comment,
zero,
int_literal_dec,
int_literal_dec_no_underscore,
@ -407,10 +406,6 @@ pub const Tokenizer = struct {
saw_at_sign,
};
fn isIdentifierChar(char: u8) bool {
return std.ascii.isAlNum(char) or char == '_';
}
pub fn next(self: *Tokenizer) Token {
if (self.pending_invalid_token) |token| {
self.pending_invalid_token = null;
@ -426,10 +421,11 @@ pub const Tokenizer = struct {
};
var seen_escape_digits: usize = undefined;
var remaining_code_units: usize = undefined;
while (self.index < self.buffer.len) : (self.index += 1) {
while (true) : (self.index += 1) {
const c = self.buffer[self.index];
switch (state) {
.start => switch (c) {
0 => break,
' ', '\n', '\t', '\r' => {
result.loc.start = self.index + 1;
},
@ -555,8 +551,9 @@ pub const Tokenizer = struct {
},
else => {
result.tag = .invalid;
result.loc.end = self.index;
self.index += 1;
break;
return result;
},
},
@ -705,18 +702,35 @@ pub const Tokenizer = struct {
self.index += 1;
break;
},
'\n', '\r' => break, // Look for this error later.
0 => {
if (self.index == self.buffer.len) {
break;
} else {
self.checkLiteralCharacter();
}
},
'\n' => {
result.tag = .invalid;
break;
},
else => self.checkLiteralCharacter(),
},
.string_literal_backslash => switch (c) {
'\n', '\r' => break, // Look for this error later.
'\n' => {
result.tag = .invalid;
break;
},
else => {
state = .string_literal;
},
},
.char_literal => switch (c) {
0 => {
result.tag = .invalid;
break;
},
'\\' => {
state = .char_literal_backslash;
},
@ -742,7 +756,7 @@ pub const Tokenizer = struct {
},
.char_literal_backslash => switch (c) {
'\n' => {
0, '\n' => {
result.tag = .invalid;
break;
},
@ -774,7 +788,6 @@ pub const Tokenizer = struct {
.char_literal_unicode_escape_saw_u => switch (c) {
'{' => {
state = .char_literal_unicode_escape;
seen_escape_digits = 0;
},
else => {
result.tag = .invalid;
@ -783,16 +796,9 @@ pub const Tokenizer = struct {
},
.char_literal_unicode_escape => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {
seen_escape_digits += 1;
},
'0'...'9', 'a'...'f', 'A'...'F' => {},
'}' => {
if (seen_escape_digits == 0) {
result.tag = .invalid;
state = .char_literal_unicode_invalid;
} else {
state = .char_literal_end;
}
state = .char_literal_end; // too many/few digits handled later
},
else => {
result.tag = .invalid;
@ -834,6 +840,7 @@ pub const Tokenizer = struct {
},
.multiline_string_literal_line => switch (c) {
0 => break,
'\n' => {
self.index += 1;
break;
@ -1025,12 +1032,19 @@ pub const Tokenizer = struct {
},
},
.line_comment_start => switch (c) {
0 => {
if (self.index != self.buffer.len) {
result.tag = .invalid;
self.index += 1;
}
break;
},
'/' => {
state = .doc_comment_start;
},
'!' => {
result.tag = .container_doc_comment;
state = .container_doc_comment;
state = .doc_comment;
},
'\n' => {
state = .start;
@ -1046,7 +1060,7 @@ pub const Tokenizer = struct {
'/' => {
state = .line_comment;
},
'\n' => {
0, '\n' => {
result.tag = .doc_comment;
break;
},
@ -1061,6 +1075,7 @@ pub const Tokenizer = struct {
},
},
.line_comment => switch (c) {
0 => break,
'\n' => {
state = .start;
result.loc.start = self.index + 1;
@ -1068,8 +1083,8 @@ pub const Tokenizer = struct {
'\t', '\r' => {},
else => self.checkLiteralCharacter(),
},
.doc_comment, .container_doc_comment => switch (c) {
'\n' => break,
.doc_comment => switch (c) {
0, '\n' => break,
'\t', '\r' => {},
else => self.checkLiteralCharacter(),
},
@ -1088,12 +1103,11 @@ pub const Tokenizer = struct {
self.index -= 1;
state = .int_literal_dec;
},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'a', 'c', 'd', 'f'...'n', 'p'...'w', 'y', 'z', 'A'...'D', 'F'...'Z' => {
result.tag = .invalid;
break;
},
else => break,
},
.int_literal_bin_no_underscore => switch (c) {
'0'...'1' => {
@ -1109,12 +1123,11 @@ pub const Tokenizer = struct {
state = .int_literal_bin_no_underscore;
},
'0'...'1' => {},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'2'...'9', 'a'...'z', 'A'...'Z' => {
result.tag = .invalid;
break;
},
else => break,
},
.int_literal_oct_no_underscore => switch (c) {
'0'...'7' => {
@ -1130,12 +1143,11 @@ pub const Tokenizer = struct {
state = .int_literal_oct_no_underscore;
},
'0'...'7' => {},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'8', '9', 'a'...'z', 'A'...'Z' => {
result.tag = .invalid;
break;
},
else => break,
},
.int_literal_dec_no_underscore => switch (c) {
'0'...'9' => {
@ -1159,12 +1171,11 @@ pub const Tokenizer = struct {
result.tag = .float_literal;
},
'0'...'9' => {},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'a'...'d', 'f'...'z', 'A'...'D', 'F'...'Z' => {
result.tag = .invalid;
break;
},
else => break,
},
.int_literal_hex_no_underscore => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {
@ -1188,12 +1199,11 @@ pub const Tokenizer = struct {
result.tag = .float_literal;
},
'0'...'9', 'a'...'f', 'A'...'F' => {},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'g'...'o', 'q'...'z', 'G'...'O', 'Q'...'Z' => {
result.tag = .invalid;
break;
},
else => break,
},
.num_dot_dec => switch (c) {
'.' => {
@ -1206,12 +1216,11 @@ pub const Tokenizer = struct {
result.tag = .float_literal;
state = .float_fraction_dec;
},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'_', 'a'...'z', 'A'...'Z' => {
result.tag = .invalid;
break;
},
else => break,
},
.num_dot_hex => switch (c) {
'.' => {
@ -1224,12 +1233,11 @@ pub const Tokenizer = struct {
result.tag = .float_literal;
state = .float_fraction_hex;
},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'_', 'g'...'z', 'G'...'Z' => {
result.tag = .invalid;
break;
},
else => break,
},
.float_fraction_dec_no_underscore => switch (c) {
'0'...'9' => {
@ -1248,12 +1256,11 @@ pub const Tokenizer = struct {
state = .float_exponent_unsigned;
},
'0'...'9' => {},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'a'...'d', 'f'...'z', 'A'...'D', 'F'...'Z' => {
result.tag = .invalid;
break;
},
else => break,
},
.float_fraction_hex_no_underscore => switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => {
@ -1272,12 +1279,11 @@ pub const Tokenizer = struct {
state = .float_exponent_unsigned;
},
'0'...'9', 'a'...'f', 'A'...'F' => {},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'g'...'o', 'q'...'z', 'G'...'O', 'Q'...'Z' => {
result.tag = .invalid;
break;
},
else => break,
},
.float_exponent_unsigned => switch (c) {
'+', '-' => {
@ -1303,130 +1309,11 @@ pub const Tokenizer = struct {
state = .float_exponent_num_no_underscore;
},
'0'...'9' => {},
else => {
if (isIdentifierChar(c)) {
result.tag = .invalid;
}
'a'...'z', 'A'...'Z' => {
result.tag = .invalid;
break;
},
},
}
} else if (self.index == self.buffer.len) {
switch (state) {
.start,
.int_literal_dec,
.int_literal_bin,
.int_literal_oct,
.int_literal_hex,
.num_dot_dec,
.num_dot_hex,
.float_fraction_dec,
.float_fraction_hex,
.float_exponent_num,
.string_literal, // find this error later
.multiline_string_literal_line,
.builtin,
.line_comment,
.line_comment_start,
=> {},
.identifier => {
if (Token.getKeyword(self.buffer[result.loc.start..self.index])) |tag| {
result.tag = tag;
}
},
.doc_comment, .doc_comment_start => {
result.tag = .doc_comment;
},
.container_doc_comment => {
result.tag = .container_doc_comment;
},
.int_literal_dec_no_underscore,
.int_literal_bin_no_underscore,
.int_literal_oct_no_underscore,
.int_literal_hex_no_underscore,
.float_fraction_dec_no_underscore,
.float_fraction_hex_no_underscore,
.float_exponent_num_no_underscore,
.float_exponent_unsigned,
.saw_at_sign,
.backslash,
.char_literal,
.char_literal_backslash,
.char_literal_hex_escape,
.char_literal_unicode_escape_saw_u,
.char_literal_unicode_escape,
.char_literal_unicode_invalid,
.char_literal_end,
.char_literal_unicode,
.string_literal_backslash,
=> {
result.tag = .invalid;
},
.equal => {
result.tag = .equal;
},
.bang => {
result.tag = .bang;
},
.minus => {
result.tag = .minus;
},
.slash => {
result.tag = .slash;
},
.zero => {
result.tag = .integer_literal;
},
.ampersand => {
result.tag = .ampersand;
},
.period => {
result.tag = .period;
},
.period_2 => {
result.tag = .ellipsis2;
},
.period_asterisk => {
result.tag = .period_asterisk;
},
.pipe => {
result.tag = .pipe;
},
.angle_bracket_angle_bracket_right => {
result.tag = .angle_bracket_angle_bracket_right;
},
.angle_bracket_right => {
result.tag = .angle_bracket_right;
},
.angle_bracket_angle_bracket_left => {
result.tag = .angle_bracket_angle_bracket_left;
},
.angle_bracket_left => {
result.tag = .angle_bracket_left;
},
.plus_percent => {
result.tag = .plus_percent;
},
.plus => {
result.tag = .plus;
},
.percent => {
result.tag = .percent;
},
.caret => {
result.tag = .caret;
},
.asterisk_percent => {
result.tag = .asterisk_percent;
},
.asterisk => {
result.tag = .asterisk;
},
.minus_percent => {
result.tag = .minus_percent;
else => break,
},
}
}
@ -1566,7 +1453,7 @@ test "tokenizer - code point literal with unicode escapes" {
, &.{ .invalid, .invalid });
try testTokenize(
\\'\u{}'
, &.{ .invalid, .invalid });
, &.{.char_literal});
try testTokenize(
\\'\u{s}'
, &.{ .invalid, .invalid });
@ -2049,15 +1936,17 @@ test "tokenizer - invalid builtin identifiers" {
try testTokenize("@0()", &.{ .invalid, .integer_literal, .l_paren, .r_paren });
}
fn testTokenize(source: []const u8, expected_tokens: []const Token.Tag) !void {
fn testTokenize(source: [:0]const u8, expected_tokens: []const Token.Tag) !void {
var tokenizer = Tokenizer.init(source);
for (expected_tokens) |expected_token_id| {
const token = tokenizer.next();
if (token.tag != expected_token_id) {
std.debug.panic("expected {s}, found {s}\n", .{ @tagName(expected_token_id), @tagName(token.tag) });
std.debug.panic("expected {s}, found {s}\n", .{
@tagName(expected_token_id), @tagName(token.tag),
});
}
}
const last_token = tokenizer.next();
try std.testing.expect(last_token.tag == .eof);
try std.testing.expect(last_token.loc.start == source.len);
try std.testing.expectEqual(Token.Tag.eof, last_token.tag);
try std.testing.expectEqual(source.len, last_token.loc.start);
}

View File

@ -34,8 +34,9 @@ string_table: std.StringHashMapUnmanaged(u32) = .{},
compile_errors: ArrayListUnmanaged(Zir.Inst.CompileErrors.Item) = .{},
/// The topmost block of the current function.
fn_block: ?*GenZir = null,
/// String table indexes, keeps track of all `@import` operands.
imports: std.AutoArrayHashMapUnmanaged(u32, void) = .{},
/// Maps string table indexes to the first `@import` ZIR instruction
/// that uses this string as the operand.
imports: std.AutoArrayHashMapUnmanaged(u32, Zir.Inst.Index) = .{},
const InnerError = error{ OutOfMemory, AnalysisFail };
@ -154,7 +155,7 @@ pub fn generate(gpa: *Allocator, tree: ast.Tree) Allocator.Error!Zir {
astgen.extra.items[imports_index] = astgen.addExtraAssumeCapacity(Zir.Inst.Imports{
.imports_len = @intCast(u32, astgen.imports.count()),
});
astgen.extra.appendSliceAssumeCapacity(astgen.imports.keys());
astgen.extra.appendSliceAssumeCapacity(astgen.imports.values());
}
return Zir{
@ -261,6 +262,23 @@ fn typeExpr(gz: *GenZir, scope: *Scope, type_node: ast.Node.Index) InnerError!Zi
return expr(gz, scope, .{ .ty = .type_type }, type_node);
}
/// Same as `expr` but fails with a compile error if the result type is `noreturn`.
fn reachableExpr(
gz: *GenZir,
scope: *Scope,
rl: ResultLoc,
node: ast.Node.Index,
src_node: ast.Node.Index,
) InnerError!Zir.Inst.Ref {
const result_inst = try expr(gz, scope, rl, node);
if (gz.refIsNoReturn(result_inst)) {
return gz.astgen.failNodeNotes(src_node, "unreachable code", .{}, &[_]u32{
try gz.astgen.errNoteNode(node, "control flow is diverted here", .{}),
});
}
return result_inst;
}
fn lvalExpr(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!Zir.Inst.Ref {
const astgen = gz.astgen;
const tree = astgen.tree;
@ -1296,22 +1314,23 @@ fn structInitExpr(
const astgen = gz.astgen;
const tree = astgen.tree;
if (struct_init.ast.fields.len == 0) {
if (struct_init.ast.type_expr == 0) {
if (struct_init.ast.type_expr == 0) {
if (struct_init.ast.fields.len == 0) {
return rvalue(gz, rl, .empty_struct, node);
}
array: {
const node_tags = tree.nodes.items(.tag);
const main_tokens = tree.nodes.items(.main_token);
const array_type: ast.full.ArrayType = switch (node_tags[struct_init.ast.type_expr]) {
.array_type => tree.arrayType(struct_init.ast.type_expr),
.array_type_sentinel => tree.arrayTypeSentinel(struct_init.ast.type_expr),
else => break :array,
};
} else array: {
const node_tags = tree.nodes.items(.tag);
const main_tokens = tree.nodes.items(.main_token);
const array_type: ast.full.ArrayType = switch (node_tags[struct_init.ast.type_expr]) {
.array_type => tree.arrayType(struct_init.ast.type_expr),
.array_type_sentinel => tree.arrayTypeSentinel(struct_init.ast.type_expr),
else => break :array,
};
const is_inferred_array_len = node_tags[array_type.ast.elem_count] == .identifier and
// This intentionally does not support `@"_"` syntax.
if (node_tags[array_type.ast.elem_count] == .identifier and
mem.eql(u8, tree.tokenSlice(main_tokens[array_type.ast.elem_count]), "_"))
{
mem.eql(u8, tree.tokenSlice(main_tokens[array_type.ast.elem_count]), "_");
if (struct_init.ast.fields.len == 0) {
if (is_inferred_array_len) {
const elem_type = try typeExpr(gz, scope, array_type.ast.elem_type);
const array_type_inst = if (array_type.ast.sentinel == 0) blk: {
break :blk try gz.addBin(.array_type, .zero_usize, elem_type);
@ -1322,11 +1341,18 @@ fn structInitExpr(
const result = try gz.addUnNode(.struct_init_empty, array_type_inst, node);
return rvalue(gz, rl, result, node);
}
const ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr);
const result = try gz.addUnNode(.struct_init_empty, ty_inst, node);
return rvalue(gz, rl, result, node);
} else {
return astgen.failNode(
struct_init.ast.type_expr,
"initializing array with struct syntax",
.{},
);
}
const ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr);
const result = try gz.addUnNode(.struct_init_empty, ty_inst, node);
return rvalue(gz, rl, result, node);
}
switch (rl) {
.discard => {
if (struct_init.ast.type_expr != 0)
@ -1570,7 +1596,7 @@ fn breakExpr(parent_gz: *GenZir, parent_scope: *Scope, node: ast.Node.Index) Inn
const defer_scope = scope.cast(Scope.Defer).?;
scope = defer_scope.parent;
const expr_node = node_datas[defer_scope.defer_node].rhs;
try unusedResultExpr(parent_gz, defer_scope.parent, expr_node);
_ = try unusedResultExpr(parent_gz, defer_scope.parent, expr_node);
},
.defer_error => scope = scope.cast(Scope.Defer).?.parent,
.top => unreachable,
@ -1623,7 +1649,7 @@ fn continueExpr(parent_gz: *GenZir, parent_scope: *Scope, node: ast.Node.Index)
const defer_scope = scope.cast(Scope.Defer).?;
scope = defer_scope.parent;
const expr_node = node_datas[defer_scope.defer_node].rhs;
try unusedResultExpr(parent_gz, defer_scope.parent, expr_node);
_ = try unusedResultExpr(parent_gz, defer_scope.parent, expr_node);
},
.defer_error => scope = scope.cast(Scope.Defer).?.parent,
.namespace => break,
@ -1679,7 +1705,7 @@ fn checkLabelRedefinition(astgen: *AstGen, parent_scope: *Scope, label: ast.Toke
}, &[_]u32{
try astgen.errNoteTok(
prev_label.token,
"previous definition is here",
"previous definition here",
.{},
),
});
@ -1785,8 +1811,23 @@ fn blockExprStmts(gz: *GenZir, parent_scope: *Scope, statements: []const ast.Nod
var block_arena = std.heap.ArenaAllocator.init(gz.astgen.gpa);
defer block_arena.deinit();
var noreturn_src_node: ast.Node.Index = 0;
var scope = parent_scope;
for (statements) |statement| {
if (noreturn_src_node != 0) {
return astgen.failNodeNotes(
statement,
"unreachable code",
.{},
&[_]u32{
try astgen.errNoteNode(
noreturn_src_node,
"control flow is diverted here",
.{},
),
},
);
}
switch (node_tags[statement]) {
// zig fmt: off
.global_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.globalVarDecl(statement)),
@ -1814,7 +1855,7 @@ fn blockExprStmts(gz: *GenZir, parent_scope: *Scope, statements: []const ast.Nod
.assign_mul => try assignOp(gz, scope, statement, .mul),
.assign_mul_wrap => try assignOp(gz, scope, statement, .mulwrap),
else => try unusedResultExpr(gz, scope, statement),
else => noreturn_src_node = try unusedResultExpr(gz, scope, statement),
// zig fmt: on
}
}
@ -1823,11 +1864,14 @@ fn blockExprStmts(gz: *GenZir, parent_scope: *Scope, statements: []const ast.Nod
try checkUsed(gz, parent_scope, scope);
}
fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: ast.Node.Index) InnerError!void {
/// Returns AST source node of the thing that is noreturn if the statement is definitely `noreturn`.
/// Otherwise returns 0.
fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: ast.Node.Index) InnerError!ast.Node.Index {
try emitDbgNode(gz, statement);
// We need to emit an error if the result is not `noreturn` or `void`, but
// we want to avoid adding the ZIR instruction if possible for performance.
const maybe_unused_result = try expr(gz, scope, .none, statement);
var noreturn_src_node: ast.Node.Index = 0;
const elide_check = if (gz.refToIndex(maybe_unused_result)) |inst| b: {
// Note that this array becomes invalid after appending more items to it
// in the above while loop.
@ -2061,15 +2105,7 @@ fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: ast.Node.Index) Inner
.extended,
=> break :b false,
// ZIR instructions that are always either `noreturn` or `void`.
.breakpoint,
.fence,
.dbg_stmt,
.ensure_result_used,
.ensure_result_non_error,
.@"export",
.set_eval_branch_quota,
.ensure_err_payload_void,
// ZIR instructions that are always `noreturn`.
.@"break",
.break_inline,
.condbr,
@ -2078,16 +2114,30 @@ fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: ast.Node.Index) Inner
.ret_node,
.ret_coerce,
.@"unreachable",
.repeat,
.repeat_inline,
.panic,
=> {
noreturn_src_node = statement;
break :b true;
},
// ZIR instructions that are always `void`.
.breakpoint,
.fence,
.dbg_stmt,
.ensure_result_used,
.ensure_result_non_error,
.@"export",
.set_eval_branch_quota,
.ensure_err_payload_void,
.store,
.store_node,
.store_to_block_ptr,
.store_to_inferred_ptr,
.resolve_inferred_alloc,
.repeat,
.repeat_inline,
.validate_struct_init_ptr,
.validate_array_init_ptr,
.panic,
.set_align_stack,
.set_cold,
.set_float_mode,
@ -2097,15 +2147,19 @@ fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: ast.Node.Index) Inner
} else switch (maybe_unused_result) {
.none => unreachable,
.void_value,
.unreachable_value,
=> true,
.unreachable_value => b: {
noreturn_src_node = statement;
break :b true;
},
.void_value => true,
else => false,
};
if (!elide_check) {
_ = try gz.addUnNode(.ensure_result_used, maybe_unused_result, statement);
}
return noreturn_src_node;
}
fn genDefers(
@ -2132,7 +2186,7 @@ fn genDefers(
const prev_in_defer = gz.in_defer;
gz.in_defer = true;
defer gz.in_defer = prev_in_defer;
try unusedResultExpr(gz, defer_scope.parent, expr_node);
_ = try unusedResultExpr(gz, defer_scope.parent, expr_node);
},
.defer_error => {
const defer_scope = scope.cast(Scope.Defer).?;
@ -2142,7 +2196,7 @@ fn genDefers(
const prev_in_defer = gz.in_defer;
gz.in_defer = true;
defer gz.in_defer = prev_in_defer;
try unusedResultExpr(gz, defer_scope.parent, expr_node);
_ = try unusedResultExpr(gz, defer_scope.parent, expr_node);
},
.namespace => unreachable,
.top => unreachable,
@ -2163,25 +2217,15 @@ fn checkUsed(
.gen_zir => scope = scope.cast(GenZir).?.parent,
.local_val => {
const s = scope.cast(Scope.LocalVal).?;
switch (s.used) {
.used => {},
.fn_param => return astgen.failTok(s.token_src, "unused function parameter", .{}),
.constant => return astgen.failTok(s.token_src, "unused local constant", .{}),
.variable => unreachable,
.loop_index => unreachable,
.capture => return astgen.failTok(s.token_src, "unused capture", .{}),
if (!s.used) {
return astgen.failTok(s.token_src, "unused {s}", .{@tagName(s.id_cat)});
}
scope = s.parent;
},
.local_ptr => {
const s = scope.cast(Scope.LocalPtr).?;
switch (s.used) {
.used => {},
.fn_param => unreachable,
.constant => return astgen.failTok(s.token_src, "unused local constant", .{}),
.variable => return astgen.failTok(s.token_src, "unused local variable", .{}),
.loop_index => return astgen.failTok(s.token_src, "unused loop index capture", .{}),
.capture => unreachable,
if (!s.used) {
return astgen.failTok(s.token_src, "unused {s}", .{@tagName(s.id_cat)});
}
scope = s.parent;
},
@ -2221,65 +2265,13 @@ fn varDecl(
const token_tags = tree.tokens.items(.tag);
const name_token = var_decl.ast.mut_token + 1;
const ident_name_raw = tree.tokenSlice(name_token);
if (mem.eql(u8, ident_name_raw, "_")) {
return astgen.failTok(name_token, "'_' used as an identifier without @\"_\" syntax", .{});
}
const ident_name = try astgen.identAsString(name_token);
// Local variables shadowing detection, including function parameters.
{
var s = scope;
while (true) switch (s.tag) {
.local_val => {
const local_val = s.cast(Scope.LocalVal).?;
if (local_val.name == ident_name) {
const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(ident_name)));
defer gpa.free(name);
return astgen.failTokNotes(name_token, "redeclaration of '{s}'", .{
name,
}, &[_]u32{
try astgen.errNoteTok(
local_val.token_src,
"previously declared here",
.{},
),
});
}
s = local_val.parent;
},
.local_ptr => {
const local_ptr = s.cast(Scope.LocalPtr).?;
if (local_ptr.name == ident_name) {
const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(ident_name)));
defer gpa.free(name);
return astgen.failTokNotes(name_token, "redeclaration of '{s}'", .{
name,
}, &[_]u32{
try astgen.errNoteTok(
local_ptr.token_src,
"previously declared here",
.{},
),
});
}
s = local_ptr.parent;
},
.namespace => {
const ns = s.cast(Scope.Namespace).?;
const decl_node = ns.decls.get(ident_name) orelse {
s = ns.parent;
continue;
};
const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(ident_name)));
defer gpa.free(name);
return astgen.failTokNotes(name_token, "local shadows declaration of '{s}'", .{
name,
}, &[_]u32{
try astgen.errNoteNode(decl_node, "declared here", .{}),
});
},
.gen_zir => s = s.cast(GenZir).?.parent,
.defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent,
.top => break,
};
}
try astgen.detectLocalShadowing(scope, ident_name, name_token);
if (var_decl.ast.init_node == 0) {
return astgen.failNode(node, "variables must be initialized", .{});
@ -2303,7 +2295,8 @@ fn varDecl(
const result_loc: ResultLoc = if (var_decl.ast.type_node != 0) .{
.ty = try typeExpr(gz, scope, var_decl.ast.type_node),
} else .none;
const init_inst = try expr(gz, scope, result_loc, var_decl.ast.init_node);
const init_inst = try reachableExpr(gz, scope, result_loc, var_decl.ast.init_node, node);
const sub_scope = try block_arena.create(Scope.LocalVal);
sub_scope.* = .{
.parent = scope,
@ -2311,7 +2304,7 @@ fn varDecl(
.name = ident_name,
.inst = init_inst,
.token_src = name_token,
.used = .constant,
.id_cat = .@"local constant",
};
return &sub_scope.base;
}
@ -2353,7 +2346,8 @@ fn varDecl(
init_scope.rl_ptr = alloc;
}
const init_result_loc: ResultLoc = .{ .block_ptr = &init_scope };
const init_inst = try expr(&init_scope, &init_scope.base, init_result_loc, var_decl.ast.init_node);
const init_inst = try reachableExpr(&init_scope, &init_scope.base, init_result_loc, var_decl.ast.init_node, node);
const zir_tags = astgen.instructions.items(.tag);
const zir_datas = astgen.instructions.items(.data);
@ -2379,7 +2373,7 @@ fn varDecl(
.name = ident_name,
.inst = init_inst,
.token_src = name_token,
.used = .constant,
.id_cat = .@"local constant",
};
return &sub_scope.base;
}
@ -2409,7 +2403,7 @@ fn varDecl(
.ptr = init_scope.rl_ptr,
.token_src = name_token,
.maybe_comptime = true,
.used = .constant,
.id_cat = .@"local constant",
};
return &sub_scope.base;
},
@ -2454,7 +2448,7 @@ fn varDecl(
resolve_inferred_alloc = alloc;
break :a .{ .alloc = alloc, .result_loc = .{ .inferred_ptr = alloc } };
};
_ = try expr(gz, scope, var_data.result_loc, var_decl.ast.init_node);
_ = try reachableExpr(gz, scope, var_data.result_loc, var_decl.ast.init_node, node);
if (resolve_inferred_alloc != .none) {
_ = try gz.addUnNode(.resolve_inferred_alloc, resolve_inferred_alloc, node);
}
@ -2466,7 +2460,7 @@ fn varDecl(
.ptr = var_data.alloc,
.token_src = name_token,
.maybe_comptime = is_comptime,
.used = .variable,
.id_cat = .@"local variable",
};
return &sub_scope.base;
},
@ -2956,7 +2950,11 @@ fn fnDecl(
var it = fn_proto.iterate(tree.*);
while (it.next()) |param| : (i += 1) {
const name_token = param.name_token orelse {
return astgen.failNode(param.type_expr, "missing parameter name", .{});
if (param.anytype_ellipsis3) |tok| {
return astgen.failTok(tok, "missing parameter name", .{});
} else {
return astgen.failNode(param.type_expr, "missing parameter name", .{});
}
};
if (param.type_expr != 0)
_ = try typeExpr(&fn_gz, params_scope, param.type_expr);
@ -2965,7 +2963,7 @@ fn fnDecl(
const param_name = try astgen.identAsString(name_token);
// Create an arg instruction. This is needed to emit a semantic analysis
// error for shadowing decls.
// TODO emit a compile error here for shadowing locals.
try astgen.detectLocalShadowing(params_scope, param_name, name_token);
const arg_inst = try fn_gz.addStrTok(.arg, param_name, name_token);
const sub_scope = try astgen.arena.create(Scope.LocalVal);
sub_scope.* = .{
@ -2974,7 +2972,7 @@ fn fnDecl(
.name = param_name,
.inst = arg_inst,
.token_src = name_token,
.used = .fn_param,
.id_cat = .@"function parameter",
};
params_scope = &sub_scope.base;
@ -4005,7 +4003,18 @@ fn containerDecl(
return astgen.failTok(comptime_token, "enum fields cannot be marked comptime", .{});
}
if (member.ast.type_expr != 0) {
return astgen.failNode(member.ast.type_expr, "enum fields do not have types", .{});
return astgen.failNodeNotes(
member.ast.type_expr,
"enum fields do not have types",
.{},
&[_]u32{
try astgen.errNoteNode(
node,
"consider 'union(enum)' here to make it a tagged union",
.{},
),
},
);
}
// Alignment expressions in enums are caught by the parser.
assert(member.ast.align_expr == 0);
@ -4523,7 +4532,7 @@ fn tryExpr(
return astgen.failNode(node, "invalid 'try' outside function scope", .{});
};
if (parent_gz.in_defer) return astgen.failNode(node, "try is not allowed inside defer expression", .{});
if (parent_gz.in_defer) return astgen.failNode(node, "'try' not allowed inside defer expression", .{});
var block_scope = parent_gz.makeSubBlock(scope);
block_scope.setBreakResultLoc(rl);
@ -4638,7 +4647,7 @@ fn orelseCatchExpr(
.name = err_name,
.inst = try then_scope.addUnNode(unwrap_code_op, operand, node),
.token_src = payload,
.used = .capture,
.id_cat = .@"capture",
};
break :blk &err_val_scope.base;
};
@ -4930,7 +4939,7 @@ fn ifExpr(
.name = ident_name,
.inst = payload_inst,
.token_src = payload_token,
.used = .capture,
.id_cat = .@"capture",
};
break :s &payload_val_scope.base;
} else {
@ -4952,7 +4961,7 @@ fn ifExpr(
.name = ident_name,
.inst = payload_inst,
.token_src = ident_token,
.used = .capture,
.id_cat = .@"capture",
};
break :s &payload_val_scope.base;
} else {
@ -4993,7 +5002,7 @@ fn ifExpr(
.name = ident_name,
.inst = payload_inst,
.token_src = error_token,
.used = .capture,
.id_cat = .@"capture",
};
break :s &payload_val_scope.base;
} else {
@ -5187,7 +5196,7 @@ fn whileExpr(
.name = ident_name,
.inst = payload_inst,
.token_src = payload_token,
.used = .capture,
.id_cat = .@"capture",
};
break :s &payload_val_scope.base;
} else {
@ -5209,7 +5218,7 @@ fn whileExpr(
.name = ident_name,
.inst = payload_inst,
.token_src = ident_token,
.used = .capture,
.id_cat = .@"capture",
};
break :s &payload_val_scope.base;
} else {
@ -5266,7 +5275,7 @@ fn whileExpr(
.name = ident_name,
.inst = payload_inst,
.token_src = error_token,
.used = .capture,
.id_cat = .@"capture",
};
break :s &payload_val_scope.base;
} else {
@ -5405,7 +5414,7 @@ fn forExpr(
.name = name_str_index,
.inst = payload_inst,
.token_src = ident,
.used = .capture,
.id_cat = .@"capture",
};
payload_sub_scope = &payload_val_scope.base;
} else if (is_ptr) {
@ -5429,7 +5438,7 @@ fn forExpr(
.ptr = index_ptr,
.token_src = index_token,
.maybe_comptime = is_inline,
.used = .loop_index,
.id_cat = .@"loop index capture",
};
break :blk &index_scope.base;
};
@ -5529,7 +5538,7 @@ fn switchExpr(
&[_]u32{
try astgen.errNoteTok(
src,
"previous else prong is here",
"previous else prong here",
.{},
),
},
@ -5542,12 +5551,12 @@ fn switchExpr(
&[_]u32{
try astgen.errNoteTok(
case_src,
"else prong is here",
"else prong here",
.{},
),
try astgen.errNoteTok(
some_underscore,
"'_' prong is here",
"'_' prong here",
.{},
),
},
@ -5570,7 +5579,7 @@ fn switchExpr(
&[_]u32{
try astgen.errNoteTok(
src,
"previous '_' prong is here",
"previous '_' prong here",
.{},
),
},
@ -5583,12 +5592,12 @@ fn switchExpr(
&[_]u32{
try astgen.errNoteTok(
some_else,
"else prong is here",
"else prong here",
.{},
),
try astgen.errNoteTok(
case_src,
"'_' prong is here",
"'_' prong here",
.{},
),
},
@ -5674,7 +5683,7 @@ fn switchExpr(
.name = capture_name,
.inst = capture,
.token_src = payload_token,
.used = .capture,
.id_cat = .@"capture",
};
break :blk &capture_val_scope.base;
};
@ -5768,7 +5777,7 @@ fn switchExpr(
.name = capture_name,
.inst = capture,
.token_src = payload_token,
.used = .capture,
.id_cat = .@"capture",
};
break :blk &capture_val_scope.base;
};
@ -6150,10 +6159,11 @@ fn identifier(
const main_tokens = tree.nodes.items(.main_token);
const ident_token = main_tokens[ident];
const ident_name = try astgen.identifierTokenString(ident_token);
if (mem.eql(u8, ident_name, "_")) {
return astgen.failNode(ident, "'_' may not be used as an identifier", .{});
const ident_name_raw = tree.tokenSlice(ident_token);
if (mem.eql(u8, ident_name_raw, "_")) {
return astgen.failNode(ident, "'_' used as an identifier without @\"_\" syntax", .{});
}
const ident_name = try astgen.identifierTokenString(ident_token);
if (simple_types.get(ident_name)) |zir_const_ref| {
return rvalue(gz, rl, zir_const_ref, ident);
@ -6197,7 +6207,7 @@ fn identifier(
const local_val = s.cast(Scope.LocalVal).?;
if (local_val.name == name_str_index) {
local_val.used = .used;
local_val.used = true;
// Captures of non-locals need to be emitted as decl_val or decl_ref.
// This *might* be capturable depending on if it is comptime known.
if (!hit_namespace) {
@ -6209,7 +6219,7 @@ fn identifier(
.local_ptr => {
const local_ptr = s.cast(Scope.LocalPtr).?;
if (local_ptr.name == name_str_index) {
local_ptr.used = .used;
local_ptr.used = true;
if (hit_namespace) {
if (local_ptr.maybe_comptime)
break
@ -6333,20 +6343,76 @@ fn charLiteral(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) !Zir.Inst.Ref {
const main_token = main_tokens[node];
const slice = tree.tokenSlice(main_token);
var bad_index: usize = undefined;
const value = std.zig.parseCharLiteral(slice, &bad_index) catch |err| switch (err) {
error.InvalidCharacter => {
const bad_byte = slice[bad_index];
switch (std.zig.parseCharLiteral(slice)) {
.success => |codepoint| {
const result = try gz.addInt(codepoint);
return rvalue(gz, rl, result, node);
},
.invalid_escape_character => |bad_index| {
return astgen.failOff(
main_token,
@intCast(u32, bad_index),
"invalid character: '{c}'\n",
.{bad_byte},
"invalid escape character: '{c}'",
.{slice[bad_index]},
);
},
};
const result = try gz.addInt(value);
return rvalue(gz, rl, result, node);
.expected_hex_digit => |bad_index| {
return astgen.failOff(
main_token,
@intCast(u32, bad_index),
"expected hex digit, found '{c}'",
.{slice[bad_index]},
);
},
.empty_unicode_escape_sequence => |bad_index| {
return astgen.failOff(
main_token,
@intCast(u32, bad_index),
"empty unicode escape sequence",
.{},
);
},
.expected_hex_digit_or_rbrace => |bad_index| {
return astgen.failOff(
main_token,
@intCast(u32, bad_index),
"expected hex digit or '}}', found '{c}'",
.{slice[bad_index]},
);
},
.unicode_escape_overflow => |bad_index| {
return astgen.failOff(
main_token,
@intCast(u32, bad_index),
"unicode escape too large to be a valid codepoint",
.{},
);
},
.expected_lbrace => |bad_index| {
return astgen.failOff(
main_token,
@intCast(u32, bad_index),
"expected '{{', found '{c}",
.{slice[bad_index]},
);
},
.expected_end => |bad_index| {
return astgen.failOff(
main_token,
@intCast(u32, bad_index),
"expected ending single quote ('), found '{c}",
.{slice[bad_index]},
);
},
.invalid_character => |bad_index| {
return astgen.failOff(
main_token,
@intCast(u32, bad_index),
"invalid byte in character literal: '{c}'",
.{slice[bad_index]},
);
},
}
}
fn integerLiteral(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref {
@ -6489,7 +6555,7 @@ fn asmExpr(
.local_val => {
const local_val = s.cast(Scope.LocalVal).?;
if (local_val.name == str_index) {
local_val.used = .used;
local_val.used = true;
break;
}
s = local_val.parent;
@ -6497,7 +6563,7 @@ fn asmExpr(
.local_ptr => {
const local_ptr = s.cast(Scope.LocalPtr).?;
if (local_ptr.name == str_index) {
local_ptr.used = .used;
local_ptr.used = true;
break;
}
s = local_ptr.parent;
@ -6585,14 +6651,14 @@ fn as(
const dest_type = try typeExpr(gz, scope, lhs);
switch (rl) {
.none, .none_or_ref, .discard, .ref, .ty => {
const result = try expr(gz, scope, .{ .ty = dest_type }, rhs);
const result = try reachableExpr(gz, scope, .{ .ty = dest_type }, rhs, node);
return rvalue(gz, rl, result, node);
},
.ptr, .inferred_ptr => |result_ptr| {
return asRlPtr(gz, scope, rl, result_ptr, rhs, dest_type);
return asRlPtr(gz, scope, rl, node, result_ptr, rhs, dest_type);
},
.block_ptr => |block_scope| {
return asRlPtr(gz, scope, rl, block_scope.rl_ptr, rhs, dest_type);
return asRlPtr(gz, scope, rl, node, block_scope.rl_ptr, rhs, dest_type);
},
}
}
@ -6646,6 +6712,7 @@ fn asRlPtr(
parent_gz: *GenZir,
scope: *Scope,
rl: ResultLoc,
src_node: ast.Node.Index,
result_ptr: Zir.Inst.Ref,
operand_node: ast.Node.Index,
dest_type: Zir.Inst.Ref,
@ -6659,7 +6726,7 @@ fn asRlPtr(
defer as_scope.instructions.deinit(astgen.gpa);
as_scope.rl_ptr = try as_scope.addBin(.coerce_result_ptr, dest_type, result_ptr);
const result = try expr(&as_scope, &as_scope.base, .{ .block_ptr = &as_scope }, operand_node);
const result = try reachableExpr(&as_scope, &as_scope.base, .{ .block_ptr = &as_scope }, operand_node, src_node);
const parent_zir = &parent_gz.instructions;
if (as_scope.rvalue_rl_count == 1) {
// Busted! This expression didn't actually need a pointer.
@ -6738,13 +6805,14 @@ fn typeOf(
return gz.astgen.failNode(node, "expected at least 1 argument, found 0", .{});
}
if (params.len == 1) {
const result = try gz.addUnNode(.typeof, try expr(gz, scope, .none, params[0]), node);
const expr_result = try reachableExpr(gz, scope, .none, params[0], node);
const result = try gz.addUnNode(.typeof, expr_result, node);
return rvalue(gz, rl, result, node);
}
const arena = gz.astgen.arena;
var items = try arena.alloc(Zir.Inst.Ref, params.len);
for (params) |param, param_i| {
items[param_i] = try expr(gz, scope, .none, param);
items[param_i] = try reachableExpr(gz, scope, .none, param, node);
}
const result = try gz.addExtendedMultiOp(.typeof_peer, node, items);
@ -6778,7 +6846,7 @@ fn builtinCall(
if (info.param_count) |expected| {
if (expected != params.len) {
const s = if (expected == 1) "" else "s";
return astgen.failNode(node, "expected {d} parameter{s}, found {d}", .{
return astgen.failNode(node, "expected {d} argument{s}, found {d}", .{
expected, s, params.len,
});
}
@ -6796,8 +6864,13 @@ fn builtinCall(
}
const str_lit_token = main_tokens[operand_node];
const str = try astgen.strLitAsString(str_lit_token);
try astgen.imports.put(astgen.gpa, str.index, {});
const result = try gz.addStrTok(.import, str.index, str_lit_token);
if (gz.refToIndex(result)) |import_inst_index| {
const gop = try astgen.imports.getOrPut(astgen.gpa, str.index);
if (!gop.found_existing) {
gop.value_ptr.* = import_inst_index;
}
}
return rvalue(gz, rl, result, node);
},
.compile_log => {
@ -6846,7 +6919,7 @@ fn builtinCall(
.local_val => {
const local_val = s.cast(Scope.LocalVal).?;
if (local_val.name == decl_name) {
local_val.used = .used;
local_val.used = true;
break;
}
s = local_val.parent;
@ -6856,7 +6929,7 @@ fn builtinCall(
if (local_ptr.name == decl_name) {
if (!local_ptr.maybe_comptime)
return astgen.failNode(params[0], "unable to export runtime-known value", .{});
local_ptr.used = .used;
local_ptr.used = true;
break;
}
s = local_ptr.parent;
@ -8423,15 +8496,15 @@ const Scope = struct {
top,
};
// either .used or the type of the var/constant
const Used = enum {
fn_param,
constant,
variable,
loop_index,
capture,
used,
/// The category of identifier. These tag names are user-visible in compile errors.
const IdCat = enum {
@"function parameter",
@"local constant",
@"local variable",
@"loop index capture",
@"capture",
};
/// This is always a `const` local and importantly the `inst` is a value type, not a pointer.
/// This structure lives as long as the AST generation of the Block
/// node that contains the variable.
@ -8446,8 +8519,9 @@ const Scope = struct {
token_src: ast.TokenIndex,
/// String table index.
name: u32,
/// has this variable been referenced?
used: Used,
id_cat: IdCat,
/// Track whether the name has been referenced.
used: bool = false,
};
/// This could be a `const` or `var` local. It has a pointer instead of a value.
@ -8464,10 +8538,12 @@ const Scope = struct {
token_src: ast.TokenIndex,
/// String table index.
name: u32,
/// true means we find out during Sema whether the value is comptime. false means it is already known at AstGen the value is runtime-known.
id_cat: IdCat,
/// true means we find out during Sema whether the value is comptime.
/// false means it is already known at AstGen the value is runtime-known.
maybe_comptime: bool,
/// has this variable been referenced?
used: Used,
/// Track whether the name has been referenced.
used: bool = false,
};
const Defer = struct {
@ -9558,6 +9634,71 @@ fn declareNewName(
}
}
/// Local variables shadowing detection, including function parameters.
fn detectLocalShadowing(
astgen: *AstGen,
scope: *Scope,
ident_name: u32,
name_token: ast.TokenIndex,
) !void {
const gpa = astgen.gpa;
var s = scope;
while (true) switch (s.tag) {
.local_val => {
const local_val = s.cast(Scope.LocalVal).?;
if (local_val.name == ident_name) {
const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(ident_name)));
defer gpa.free(name);
return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{
@tagName(local_val.id_cat), name,
}, &[_]u32{
try astgen.errNoteTok(
local_val.token_src,
"previous declaration here",
.{},
),
});
}
s = local_val.parent;
},
.local_ptr => {
const local_ptr = s.cast(Scope.LocalPtr).?;
if (local_ptr.name == ident_name) {
const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(ident_name)));
defer gpa.free(name);
return astgen.failTokNotes(name_token, "redeclaration of {s} '{s}'", .{
@tagName(local_ptr.id_cat), name,
}, &[_]u32{
try astgen.errNoteTok(
local_ptr.token_src,
"previous declaration here",
.{},
),
});
}
s = local_ptr.parent;
},
.namespace => {
const ns = s.cast(Scope.Namespace).?;
const decl_node = ns.decls.get(ident_name) orelse {
s = ns.parent;
continue;
};
const name = try gpa.dupe(u8, mem.spanZ(astgen.nullTerminatedString(ident_name)));
defer gpa.free(name);
return astgen.failTokNotes(name_token, "local shadows declaration of '{s}'", .{
name,
}, &[_]u32{
try astgen.errNoteNode(decl_node, "declared here", .{}),
});
},
.gen_zir => s = s.cast(GenZir).?.parent,
.defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent,
.top => break,
};
}
fn advanceSourceCursor(astgen: *AstGen, source: []const u8, end: usize) void {
var i = astgen.source_offset;
var line = astgen.source_line;

View File

@ -670,6 +670,7 @@ pub const InitOptions = struct {
use_llvm: ?bool = null,
use_lld: ?bool = null,
use_clang: ?bool = null,
use_stage1: ?bool = null,
rdynamic: bool = false,
strip: bool = false,
single_threaded: bool = false,
@ -807,8 +808,22 @@ pub fn create(gpa: *Allocator, options: InitOptions) !*Compilation {
const ofmt = options.object_format orelse options.target.getObjectFormat();
const use_stage1 = options.use_stage1 orelse blk: {
if (build_options.omit_stage2)
break :blk true;
if (options.use_llvm) |use_llvm| {
if (!use_llvm) {
break :blk false;
}
}
break :blk build_options.is_stage1;
};
// Make a decision on whether to use LLVM or our own backend.
const use_llvm = if (options.use_llvm) |explicit| explicit else blk: {
const use_llvm = build_options.have_llvm and blk: {
if (options.use_llvm) |explicit|
break :blk explicit;
// If we have no zig code to compile, no need for LLVM.
if (options.root_pkg == null)
break :blk false;
@ -817,18 +832,24 @@ pub fn create(gpa: *Allocator, options: InitOptions) !*Compilation {
if (ofmt == .c)
break :blk false;
// If we are the stage1 compiler, we depend on the stage1 c++ llvm backend
// The stage1 compiler depends on the stage1 C++ LLVM backend
// to compile zig code.
if (build_options.is_stage1)
if (use_stage1)
break :blk true;
// Prefer LLVM for release builds as long as it supports the target architecture.
if (options.optimize_mode != .Debug and target_util.hasLlvmSupport(options.target))
break :blk true;
// We would want to prefer LLVM for release builds when it is available, however
// we don't have an LLVM backend yet :)
// We would also want to prefer LLVM for architectures that we don't have self-hosted support for too.
break :blk false;
};
if (!use_llvm and options.machine_code_model != .default) {
return error.MachineCodeModelNotSupported;
if (!use_llvm) {
if (options.use_llvm == true) {
return error.ZigCompilerNotBuiltWithLLVMExtensions;
}
if (options.machine_code_model != .default) {
return error.MachineCodeModelNotSupportedWithoutLlvm;
}
}
const tsan = options.want_tsan orelse false;
@ -1344,6 +1365,7 @@ pub fn create(gpa: *Allocator, options: InitOptions) !*Compilation {
.subsystem = options.subsystem,
.is_test = options.is_test,
.wasi_exec_model = wasi_exec_model,
.use_stage1 = use_stage1,
});
errdefer bin_file.destroy();
comp.* = .{
@ -1486,9 +1508,9 @@ pub fn create(gpa: *Allocator, options: InitOptions) !*Compilation {
try comp.work_queue.writeItem(.libtsan);
}
// The `is_stage1` condition is here only because stage2 cannot yet build compiler-rt.
// The `use_stage1` condition is here only because stage2 cannot yet build compiler-rt.
// Once it is capable this condition should be removed.
if (build_options.is_stage1) {
if (comp.bin_file.options.use_stage1) {
if (comp.bin_file.options.include_compiler_rt) {
if (is_exe_or_dyn_lib) {
try comp.work_queue.writeItem(.{ .compiler_rt_lib = {} });
@ -1519,7 +1541,7 @@ pub fn create(gpa: *Allocator, options: InitOptions) !*Compilation {
}
}
if (build_options.is_stage1 and comp.bin_file.options.use_llvm) {
if (comp.bin_file.options.use_stage1 and comp.bin_file.options.module != null) {
try comp.work_queue.writeItem(.{ .stage1_module = {} });
}
@ -1625,8 +1647,7 @@ pub fn update(self: *Compilation) !void {
self.c_object_work_queue.writeItemAssumeCapacity(key);
}
const use_stage1 = build_options.omit_stage2 or
(build_options.is_stage1 and self.bin_file.options.use_llvm);
const use_stage1 = build_options.is_stage1 and self.bin_file.options.use_stage1;
if (self.bin_file.options.module) |module| {
module.compile_log_text.shrinkAndFree(module.gpa, 0);
module.generation += 1;
@ -1921,7 +1942,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor
// (at least for now) single-threaded main work queue. However, C object compilation
// only needs to be finished by the end of this function.
var zir_prog_node = main_progress_node.start("AST Lowering", self.astgen_work_queue.count);
var zir_prog_node = main_progress_node.start("AST Lowering", 0);
defer zir_prog_node.end();
var c_obj_prog_node = main_progress_node.start("Compile C Objects", self.c_source_files.len);
@ -1937,7 +1958,7 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor
while (self.astgen_work_queue.readItem()) |file| {
self.astgen_wait_group.start();
try self.thread_pool.spawn(workerAstGenFile, .{
self, file, &zir_prog_node, &self.astgen_wait_group,
self, file, &zir_prog_node, &self.astgen_wait_group, .root,
});
}
@ -1949,13 +1970,18 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor
}
}
const use_stage1 = build_options.omit_stage2 or
(build_options.is_stage1 and self.bin_file.options.use_llvm);
const use_stage1 = build_options.is_stage1 and self.bin_file.options.use_stage1;
if (!use_stage1) {
// Iterate over all the files and look for outdated and deleted declarations.
if (self.bin_file.options.module) |mod| {
try mod.processOutdatedAndDeletedDecls();
}
} else if (self.bin_file.options.module) |mod| {
// If there are any AstGen compile errors, report them now to avoid
// hitting stage1 bugs.
if (mod.failed_files.count() != 0) {
return;
}
}
while (self.work_queue.readItem()) |work_item| switch (work_item) {
@ -2284,11 +2310,20 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor
};
}
const AstGenSrc = union(enum) {
root,
import: struct {
importing_file: *Module.Scope.File,
import_inst: Zir.Inst.Index,
},
};
fn workerAstGenFile(
comp: *Compilation,
file: *Module.Scope.File,
prog_node: *std.Progress.Node,
wg: *WaitGroup,
src: AstGenSrc,
) void {
defer wg.finish();
@ -2301,7 +2336,7 @@ fn workerAstGenFile(
error.AnalysisFail => return,
else => {
file.status = .retryable_failure;
comp.reportRetryableAstGenError(file, err) catch |oom| switch (oom) {
comp.reportRetryableAstGenError(src, file, err) catch |oom| switch (oom) {
// Swallowing this error is OK because it's implied to be OOM when
// there is a missing `failed_files` error message.
error.OutOfMemory => {},
@ -2318,8 +2353,9 @@ fn workerAstGenFile(
if (imports_index != 0) {
const imports_len = file.zir.extra[imports_index];
for (file.zir.extra[imports_index + 1 ..][0..imports_len]) |str_index| {
const import_path = file.zir.nullTerminatedString(str_index);
for (file.zir.extra[imports_index + 1 ..][0..imports_len]) |import_inst| {
const inst_data = file.zir.instructions.items(.data)[import_inst].str_tok;
const import_path = inst_data.get(file.zir);
const import_result = blk: {
const lock = comp.mutex.acquire();
@ -2331,9 +2367,13 @@ fn workerAstGenFile(
log.debug("AstGen of {s} has import '{s}'; queuing AstGen of {s}", .{
file.sub_file_path, import_path, import_result.file.sub_file_path,
});
const sub_src: AstGenSrc = .{ .import = .{
.importing_file = file,
.import_inst = import_inst,
} };
wg.start();
comp.thread_pool.spawn(workerAstGenFile, .{
comp, import_result.file, prog_node, wg,
comp, import_result.file, prog_node, wg, sub_src,
}) catch {
wg.finish();
continue;
@ -2544,6 +2584,7 @@ fn reportRetryableCObjectError(
fn reportRetryableAstGenError(
comp: *Compilation,
src: AstGenSrc,
file: *Module.Scope.File,
err: anyerror,
) error{OutOfMemory}!void {
@ -2552,22 +2593,38 @@ fn reportRetryableAstGenError(
file.status = .retryable_failure;
const src_loc: Module.SrcLoc = .{
.file_scope = file,
.parent_decl_node = 0,
.lazy = .entire_file,
const src_loc: Module.SrcLoc = switch (src) {
.root => .{
.file_scope = file,
.parent_decl_node = 0,
.lazy = .entire_file,
},
.import => |info| blk: {
const importing_file = info.importing_file;
const import_inst = info.import_inst;
const inst_data = importing_file.zir.instructions.items(.data)[import_inst].str_tok;
break :blk .{
.file_scope = importing_file,
.parent_decl_node = 0,
.lazy = .{ .token_offset = inst_data.src_tok },
};
},
};
const err_msg = if (file.pkg.root_src_directory.path) |dir_path|
try Module.ErrorMsg.create(
gpa,
src_loc,
"unable to load {s}" ++ std.fs.path.sep_str ++ "{s}: {s}",
.{ dir_path, file.sub_file_path, @errorName(err) },
"unable to load '{'}" ++ std.fs.path.sep_str ++ "{'}': {s}",
.{
std.zig.fmtEscapes(dir_path),
std.zig.fmtEscapes(file.sub_file_path),
@errorName(err),
},
)
else
try Module.ErrorMsg.create(gpa, src_loc, "unable to load {s}: {s}", .{
file.sub_file_path, @errorName(err),
try Module.ErrorMsg.create(gpa, src_loc, "unable to load '{'}': {s}", .{
std.zig.fmtEscapes(file.sub_file_path), @errorName(err),
});
errdefer err_msg.destroy(gpa);
@ -3486,8 +3543,7 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) Alloc
const target = comp.getTarget();
const generic_arch_name = target.cpu.arch.genericName();
const use_stage1 = build_options.omit_stage2 or
(build_options.is_stage1 and comp.bin_file.options.use_llvm);
const use_stage1 = build_options.is_stage1 and comp.bin_file.options.use_stage1;
@setEvalBranchQuota(4000);
try buffer.writer().print(

View File

@ -2466,6 +2466,7 @@ pub fn astGenFile(mod: *Module, file: *Scope.File) !void {
defer msg.deinit();
const token_starts = file.tree.tokens.items(.start);
const token_tags = file.tree.tokens.items(.tag);
try file.tree.renderError(parse_err, msg.writer());
const err_msg = try gpa.create(ErrorMsg);
@ -2477,6 +2478,15 @@ pub fn astGenFile(mod: *Module, file: *Scope.File) !void {
},
.msg = msg.toOwnedSlice(),
};
if (token_tags[parse_err.token] == .invalid) {
const bad_off = @intCast(u32, file.tree.tokenSlice(parse_err.token).len);
const byte_abs = token_starts[parse_err.token] + bad_off;
try mod.errNoteNonLazy(.{
.file_scope = file,
.parent_decl_node = 0,
.lazy = .{ .byte_abs = byte_abs },
}, err_msg, "invalid byte: '{'}'", .{std.zig.fmtEscapes(source[byte_abs..][0..1])});
}
{
const lock = comp.mutex.acquire();

View File

@ -139,9 +139,15 @@ pub fn renderAsTextToFile(
if (imports_index != 0) {
try fs_file.writeAll("Imports:\n");
const imports_len = scope_file.zir.extra[imports_index];
for (scope_file.zir.extra[imports_index + 1 ..][0..imports_len]) |str_index| {
const import_path = scope_file.zir.nullTerminatedString(str_index);
try fs_file.writer().print(" {s}\n", .{import_path});
for (scope_file.zir.extra[imports_index + 1 ..][0..imports_len]) |import_inst| {
const inst_data = writer.code.instructions.items(.data)[import_inst].str_tok;
const src = inst_data.src();
const import_path = inst_data.get(writer.code);
try fs_file.writer().print(" @import(\"{}\") ", .{
std.zig.fmtEscapes(import_path),
});
try writer.writeSrc(fs_file.writer(), src);
try fs_file.writer().writeAll("\n");
}
}
}
@ -2767,9 +2773,10 @@ pub const Inst = struct {
};
};
/// Trailing: for each `imports_len` there is a string table index.
/// Trailing: for each `imports_len` there is an instruction index
/// to an import instruction.
pub const Imports = struct {
imports_len: u32,
imports_len: Zir.Inst.Index,
};
};

View File

@ -92,6 +92,7 @@ pub const Options = struct {
each_lib_rpath: bool,
disable_lld_caching: bool,
is_test: bool,
use_stage1: bool,
major_subsystem_version: ?u32,
minor_subsystem_version: ?u32,
gc_sections: ?bool = null,
@ -181,7 +182,7 @@ pub const File = struct {
/// rewriting it. A malicious file is detected as incremental link failure
/// and does not cause Illegal Behavior. This operation is not atomic.
pub fn openPath(allocator: *Allocator, options: Options) !*File {
const use_stage1 = build_options.is_stage1 and options.use_llvm;
const use_stage1 = build_options.is_stage1 and options.use_stage1;
if (use_stage1 or options.emit == null) {
return switch (options.object_format) {
.coff, .pe => &(try Coff.createEmpty(allocator, options)).base,
@ -507,7 +508,7 @@ pub const File = struct {
// If there is no Zig code to compile, then we should skip flushing the output file because it
// will not be part of the linker line anyway.
const module_obj_path: ?[]const u8 = if (base.options.module) |module| blk: {
const use_stage1 = build_options.is_stage1 and base.options.use_llvm;
const use_stage1 = build_options.is_stage1 and base.options.use_stage1;
if (use_stage1) {
const obj_basename = try std.zig.binNameAlloc(arena, .{
.root_name = base.options.root_name,

View File

@ -606,7 +606,7 @@ fn linkWithZld(self: *MachO, comp: *Compilation) !void {
// If there is no Zig code to compile, then we should skip flushing the output file because it
// will not be part of the linker line anyway.
const module_obj_path: ?[]const u8 = if (self.base.options.module) |module| blk: {
const use_stage1 = build_options.is_stage1 and self.base.options.use_llvm;
const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1;
if (use_stage1) {
const obj_basename = try std.zig.binNameAlloc(arena, .{
.root_name = self.base.options.root_name,

View File

@ -556,7 +556,7 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void {
// If there is no Zig code to compile, then we should skip flushing the output file because it
// will not be part of the linker line anyway.
const module_obj_path: ?[]const u8 = if (self.base.options.module) |module| blk: {
const use_stage1 = build_options.is_stage1 and self.base.options.use_llvm;
const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1;
if (use_stage1) {
const obj_basename = try std.zig.binNameAlloc(arena, .{
.root_name = self.base.options.root_name,

View File

@ -233,7 +233,7 @@ pub fn mainArgs(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !v
} else if (mem.eql(u8, cmd, "build")) {
return cmdBuild(gpa, arena, cmd_args);
} else if (mem.eql(u8, cmd, "fmt")) {
return cmdFmt(gpa, cmd_args);
return cmdFmt(gpa, arena, cmd_args);
} else if (mem.eql(u8, cmd, "libc")) {
return cmdLibC(gpa, cmd_args);
} else if (mem.eql(u8, cmd, "init-exe")) {
@ -350,9 +350,11 @@ const usage_build_generic =
\\ -funwind-tables Always produce unwind table entries for all functions
\\ -fno-unwind-tables Never produce unwind table entries
\\ -fLLVM Force using LLVM as the codegen backend
\\ -fno-LLVM Prevent using LLVM as a codegen backend
\\ -fno-LLVM Prevent using LLVM as the codegen backend
\\ -fClang Force using Clang as the C/C++ compilation backend
\\ -fno-Clang Prevent using Clang as the C/C++ compilation backend
\\ -fstage1 Force using bootstrap compiler as the codegen backend
\\ -fno-stage1 Prevent using bootstrap compiler as the codegen backend
\\ --strip Omit debug symbols
\\ --single-threaded Code assumes it is only used single-threaded
\\ -ofmt=[mode] Override target object format
@ -602,6 +604,7 @@ fn buildOutputType(
var use_llvm: ?bool = null;
var use_lld: ?bool = null;
var use_clang: ?bool = null;
var use_stage1: ?bool = null;
var link_eh_frame_hdr = false;
var link_emit_relocs = false;
var each_lib_rpath: ?bool = null;
@ -975,6 +978,10 @@ fn buildOutputType(
use_clang = true;
} else if (mem.eql(u8, arg, "-fno-Clang")) {
use_clang = false;
} else if (mem.eql(u8, arg, "-fstage1")) {
use_stage1 = true;
} else if (mem.eql(u8, arg, "-fno-stage1")) {
use_stage1 = false;
} else if (mem.eql(u8, arg, "-rdynamic")) {
rdynamic = true;
} else if (mem.eql(u8, arg, "-fsoname")) {
@ -2020,6 +2027,7 @@ fn buildOutputType(
.use_llvm = use_llvm,
.use_lld = use_lld,
.use_clang = use_clang,
.use_stage1 = use_stage1,
.rdynamic = rdynamic,
.linker_script = linker_script,
.version_script = version_script,
@ -3031,12 +3039,13 @@ const Fmt = struct {
check_ast: bool,
color: Color,
gpa: *Allocator,
arena: *Allocator,
out_buffer: std.ArrayList(u8),
const SeenMap = std.AutoHashMap(fs.File.INode, void);
};
pub fn cmdFmt(gpa: *Allocator, args: []const []const u8) !void {
pub fn cmdFmt(gpa: *Allocator, arena: *Allocator, args: []const []const u8) !void {
var color: Color = .auto;
var stdin_flag: bool = false;
var check_flag: bool = false;
@ -3094,7 +3103,7 @@ pub fn cmdFmt(gpa: *Allocator, args: []const []const u8) !void {
defer tree.deinit(gpa);
for (tree.errors) |parse_error| {
try printErrMsgToStdErr(gpa, parse_error, tree, "<stdin>", color);
try printErrMsgToStdErr(gpa, arena, parse_error, tree, "<stdin>", color);
}
var has_ast_error = false;
if (check_ast_flag) {
@ -3162,6 +3171,7 @@ pub fn cmdFmt(gpa: *Allocator, args: []const []const u8) !void {
var fmt = Fmt{
.gpa = gpa,
.arena = arena,
.seen = Fmt.SeenMap.init(gpa),
.any_error = false,
.check_ast = check_ast_flag,
@ -3285,7 +3295,7 @@ fn fmtPathFile(
defer tree.deinit(fmt.gpa);
for (tree.errors) |parse_error| {
try printErrMsgToStdErr(fmt.gpa, parse_error, tree, file_path, fmt.color);
try printErrMsgToStdErr(fmt.gpa, fmt.arena, parse_error, tree, file_path, fmt.color);
}
if (tree.errors.len != 0) {
fmt.any_error = true;
@ -3366,12 +3376,14 @@ fn fmtPathFile(
fn printErrMsgToStdErr(
gpa: *mem.Allocator,
arena: *mem.Allocator,
parse_error: ast.Error,
tree: ast.Tree,
path: []const u8,
color: Color,
) !void {
const lok_token = parse_error.token;
const token_tags = tree.tokens.items(.tag);
const start_loc = tree.tokenLocation(0, lok_token);
const source_line = tree.source[start_loc.line_start..start_loc.line_end];
@ -3381,6 +3393,27 @@ fn printErrMsgToStdErr(
try tree.renderError(parse_error, writer);
const text = text_buf.items;
var notes_buffer: [1]Compilation.AllErrors.Message = undefined;
var notes_len: usize = 0;
if (token_tags[parse_error.token] == .invalid) {
const bad_off = @intCast(u32, tree.tokenSlice(parse_error.token).len);
const byte_offset = @intCast(u32, start_loc.line_start) + bad_off;
notes_buffer[notes_len] = .{
.src = .{
.src_path = path,
.msg = try std.fmt.allocPrint(arena, "invalid byte: '{'}'", .{
std.zig.fmtEscapes(tree.source[byte_offset..][0..1]),
}),
.byte_offset = byte_offset,
.line = @intCast(u32, start_loc.line),
.column = @intCast(u32, start_loc.column) + bad_off,
.source_line = source_line,
},
};
notes_len += 1;
}
const message: Compilation.AllErrors.Message = .{
.src = .{
.src_path = path,
@ -3389,6 +3422,7 @@ fn printErrMsgToStdErr(
.line = @intCast(u32, start_loc.line),
.column = @intCast(u32, start_loc.column),
.source_line = source_line,
.notes = notes_buffer[0..notes_len],
},
};
@ -3915,7 +3949,7 @@ pub fn cmdAstCheck(
defer file.tree.deinit(gpa);
for (file.tree.errors) |parse_error| {
try printErrMsgToStdErr(gpa, parse_error, file.tree, file.sub_file_path, color);
try printErrMsgToStdErr(gpa, arena, parse_error, file.tree, file.sub_file_path, color);
}
if (file.tree.errors.len != 0) {
process.exit(1);
@ -4041,7 +4075,7 @@ pub fn cmdChangelist(
defer file.tree.deinit(gpa);
for (file.tree.errors) |parse_error| {
try printErrMsgToStdErr(gpa, parse_error, file.tree, old_source_file, .auto);
try printErrMsgToStdErr(gpa, arena, parse_error, file.tree, old_source_file, .auto);
}
if (file.tree.errors.len != 0) {
process.exit(1);
@ -4080,7 +4114,7 @@ pub fn cmdChangelist(
defer new_tree.deinit(gpa);
for (new_tree.errors) |parse_error| {
try printErrMsgToStdErr(gpa, parse_error, new_tree, new_source_file, .auto);
try printErrMsgToStdErr(gpa, arena, parse_error, new_tree, new_source_file, .auto);
}
if (new_tree.errors.len != 0) {
process.exit(1);

View File

@ -7,6 +7,7 @@ const assert = std.debug.assert;
const mem = std.mem;
const CrossTarget = std.zig.CrossTarget;
const Target = std.Target;
const builtin = @import("builtin");
const build_options = @import("build_options");
const stage2 = @import("main.zig");
@ -16,16 +17,19 @@ const translate_c = @import("translate_c.zig");
const target_util = @import("target.zig");
comptime {
assert(std.builtin.link_libc);
assert(builtin.link_libc);
assert(build_options.is_stage1);
assert(build_options.have_llvm);
_ = @import("compiler_rt");
if (!builtin.is_test) {
_ = @import("compiler_rt");
@export(main, .{ .name = "main" });
}
}
pub const log = stage2.log;
pub const log_level = stage2.log_level;
pub export fn main(argc: c_int, argv: [*][*:0]u8) c_int {
pub fn main(argc: c_int, argv: [*][*:0]u8) callconv(.C) c_int {
std.os.argv = argv[0..@intCast(usize, argc)];
std.debug.maybeEnableSegfaultHandler();
@ -41,7 +45,7 @@ pub export fn main(argc: c_int, argv: [*][*:0]u8) c_int {
for (args) |*arg, i| {
arg.* = mem.spanZ(argv[i]);
}
if (std.builtin.mode == .Debug) {
if (builtin.mode == .Debug) {
stage2.mainArgs(gpa, arena, args) catch unreachable;
} else {
stage2.mainArgs(gpa, arena, args) catch |err| fatal("{s}", .{@errorName(err)});
@ -147,6 +151,7 @@ pub const Module = extern struct {
}
};
pub const os_init = zig_stage1_os_init;
extern fn zig_stage1_os_init() void;
pub const create = zig_stage1_create;

View File

@ -2733,10 +2733,6 @@ struct IrInstSrc {
IrInst base;
IrInstSrcId id;
// true if this instruction was generated by zig and not from user code
// this matters for the "unreachable code" compile error
bool is_gen;
bool is_noreturn;
// When analyzing IR, instructions that point to this instruction in the "old ir"
// can find the instruction that corresponds to this value in the "new ir"

View File

@ -3915,7 +3915,7 @@ static void add_top_level_decl(CodeGen *g, ScopeDecls *decls_scope, Tld *tld) {
}
}
ErrorMsg *msg = add_node_error(g, tld->source_node, buf_sprintf("redefinition of '%s'", buf_ptr(tld->name)));
add_error_note(g, msg, other_tld->source_node, buf_sprintf("previous definition is here"));
add_error_note(g, msg, other_tld->source_node, buf_sprintf("previous definition here"));
return;
}
@ -4176,7 +4176,7 @@ ZigVar *add_variable(CodeGen *g, AstNode *source_node, Scope *parent_scope, Buf
if (existing_var->var_type == nullptr || !type_is_invalid(existing_var->var_type)) {
ErrorMsg *msg = add_node_error(g, source_node,
buf_sprintf("redeclaration of variable '%s'", buf_ptr(name)));
add_error_note(g, msg, existing_var->decl_node, buf_sprintf("previous declaration is here"));
add_error_note(g, msg, existing_var->decl_node, buf_sprintf("previous declaration here"));
}
variable_entry->var_type = g->builtin_types.entry_invalid;
} else {
@ -4205,7 +4205,7 @@ ZigVar *add_variable(CodeGen *g, AstNode *source_node, Scope *parent_scope, Buf
if (want_err_msg) {
ErrorMsg *msg = add_node_error(g, source_node,
buf_sprintf("redefinition of '%s'", buf_ptr(name)));
add_error_note(g, msg, tld->source_node, buf_sprintf("previous definition is here"));
add_error_note(g, msg, tld->source_node, buf_sprintf("previous definition here"));
}
variable_entry->var_type = g->builtin_types.entry_invalid;
}

View File

@ -55,7 +55,17 @@ static ErrorMsg *exec_add_error_node(CodeGen *codegen, Stage1Zir *exec, AstNode
static bool instr_is_unreachable(IrInstSrc *instruction) {
return instruction->is_noreturn;
switch (instruction->id) {
case IrInstSrcIdCondBr:
case IrInstSrcIdReturn:
case IrInstSrcIdBr:
case IrInstSrcIdUnreachable:
case IrInstSrcIdSwitchBr:
case IrInstSrcIdPanic:
return true;
default:
return false;
}
}
void destroy_instruction_src(IrInstSrc *inst) {
@ -947,7 +957,6 @@ static IrInstSrc *ir_build_cond_br(Stage1AstGen *ag, Scope *scope, AstNode *sour
Stage1ZirBasicBlock *then_block, Stage1ZirBasicBlock *else_block, IrInstSrc *is_comptime)
{
IrInstSrcCondBr *inst = ir_build_instruction<IrInstSrcCondBr>(ag, scope, source_node);
inst->base.is_noreturn = true;
inst->condition = condition;
inst->then_block = then_block;
inst->else_block = else_block;
@ -963,7 +972,6 @@ static IrInstSrc *ir_build_cond_br(Stage1AstGen *ag, Scope *scope, AstNode *sour
static IrInstSrc *ir_build_return_src(Stage1AstGen *ag, Scope *scope, AstNode *source_node, IrInstSrc *operand) {
IrInstSrcReturn *inst = ir_build_instruction<IrInstSrcReturn>(ag, scope, source_node);
inst->base.is_noreturn = true;
inst->operand = operand;
if (operand != nullptr) ir_ref_instruction(operand, ag->current_basic_block);
@ -1303,7 +1311,6 @@ static IrInstSrc *ir_build_br(Stage1AstGen *ag, Scope *scope, AstNode *source_no
Stage1ZirBasicBlock *dest_block, IrInstSrc *is_comptime)
{
IrInstSrcBr *inst = ir_build_instruction<IrInstSrcBr>(ag, scope, source_node);
inst->base.is_noreturn = true;
inst->dest_block = dest_block;
inst->is_comptime = is_comptime;
@ -1418,7 +1425,6 @@ static IrInstSrc *ir_build_container_init_fields(Stage1AstGen *ag, Scope *scope,
static IrInstSrc *ir_build_unreachable(Stage1AstGen *ag, Scope *scope, AstNode *source_node) {
IrInstSrcUnreachable *inst = ir_build_instruction<IrInstSrcUnreachable>(ag, scope, source_node);
inst->base.is_noreturn = true;
return &inst->base;
}
@ -1718,7 +1724,6 @@ static IrInstSrcSwitchBr *ir_build_switch_br_src(Stage1AstGen *ag, Scope *scope,
IrInstSrc *is_comptime, IrInstSrc *switch_prongs_void)
{
IrInstSrcSwitchBr *instruction = ir_build_instruction<IrInstSrcSwitchBr>(ag, scope, source_node);
instruction->base.is_noreturn = true;
instruction->target_value = target_value;
instruction->else_block = else_block;
instruction->case_count = case_count;
@ -2439,7 +2444,6 @@ static IrInstSrc *ir_build_decl_ref(Stage1AstGen *ag, Scope *scope, AstNode *sou
static IrInstSrc *ir_build_panic_src(Stage1AstGen *ag, Scope *scope, AstNode *source_node, IrInstSrc *msg) {
IrInstSrcPanic *instruction = ir_build_instruction<IrInstSrcPanic>(ag, scope, source_node);
instruction->base.is_noreturn = true;
instruction->msg = msg;
ir_ref_instruction(msg, ag->current_basic_block);
@ -2557,7 +2561,6 @@ static IrInstSrc *ir_build_reset_result(Stage1AstGen *ag, Scope *scope, AstNode
{
IrInstSrcResetResult *instruction = ir_build_instruction<IrInstSrcResetResult>(ag, scope, source_node);
instruction->result_loc = result_loc;
instruction->base.is_gen = true;
return &instruction->base;
}
@ -2737,7 +2740,6 @@ static IrInstSrc *ir_build_alloca_src(Stage1AstGen *ag, Scope *scope, AstNode *s
IrInstSrc *align, const char *name_hint, IrInstSrc *is_comptime)
{
IrInstSrcAlloca *instruction = ir_build_instruction<IrInstSrcAlloca>(ag, scope, source_node);
instruction->base.is_gen = true;
instruction->align = align;
instruction->name_hint = name_hint;
instruction->is_comptime = is_comptime;
@ -2752,7 +2754,6 @@ static IrInstSrc *ir_build_end_expr(Stage1AstGen *ag, Scope *scope, AstNode *sou
IrInstSrc *value, ResultLoc *result_loc)
{
IrInstSrcEndExpr *instruction = ir_build_instruction<IrInstSrcEndExpr>(ag, scope, source_node);
instruction->base.is_gen = true;
instruction->value = value;
instruction->result_loc = result_loc;
@ -2885,11 +2886,6 @@ static void ir_count_defers(Stage1AstGen *ag, Scope *inner_scope, Scope *outer_s
}
}
static IrInstSrc *ir_mark_gen(IrInstSrc *instruction) {
instruction->is_gen = true;
return instruction;
}
static bool astgen_defers_for_block(Stage1AstGen *ag, Scope *inner_scope, Scope *outer_scope, bool *is_noreturn, IrInstSrc *err_value) {
Scope *scope = inner_scope;
if (is_noreturn != nullptr) *is_noreturn = false;
@ -2945,11 +2941,11 @@ static bool astgen_defers_for_block(Stage1AstGen *ag, Scope *inner_scope, Scope
if (defer_expr_value == ag->codegen->invalid_inst_src)
return ag->codegen->invalid_inst_src;
if (defer_expr_value->is_noreturn) {
if (instr_is_unreachable(defer_expr_value)) {
if (is_noreturn != nullptr) *is_noreturn = true;
} else {
ir_mark_gen(ir_build_check_statement_is_void(ag, defer_expr_scope, defer_expr_node,
defer_expr_value));
ir_build_check_statement_is_void(ag, defer_expr_scope, defer_expr_node,
defer_expr_value);
}
scope = scope->parent;
continue;
@ -3047,7 +3043,7 @@ static IrInstSrc *astgen_return(Stage1AstGen *ag, Scope *scope, AstNode *node, L
ir_build_end_expr(ag, scope, node, return_value, &result_loc_ret->base);
}
ir_mark_gen(ir_build_add_implicit_return_type(ag, scope, node, return_value, result_loc_ret));
ir_build_add_implicit_return_type(ag, scope, node, return_value, result_loc_ret);
size_t defer_counts[2];
ir_count_defers(ag, scope, outer_scope, defer_counts);
@ -3074,7 +3070,7 @@ static IrInstSrc *astgen_return(Stage1AstGen *ag, Scope *scope, AstNode *node, L
is_comptime = ir_build_test_comptime(ag, scope, node, is_err);
}
ir_mark_gen(ir_build_cond_br(ag, scope, node, is_err, err_block, ok_block, is_comptime));
ir_build_cond_br(ag, scope, node, is_err, err_block, ok_block, is_comptime);
Stage1ZirBasicBlock *ret_stmt_block = ir_create_basic_block(ag, scope, "RetStmt");
ir_set_cursor_at_end_and_append_block(ag, err_block);
@ -3112,12 +3108,12 @@ static IrInstSrc *astgen_return(Stage1AstGen *ag, Scope *scope, AstNode *node, L
} else {
is_comptime = ir_build_test_comptime(ag, scope, node, is_err_val);
}
ir_mark_gen(ir_build_cond_br(ag, scope, node, is_err_val, return_block, continue_block, is_comptime));
ir_build_cond_br(ag, scope, node, is_err_val, return_block, continue_block, is_comptime);
ir_set_cursor_at_end_and_append_block(ag, return_block);
IrInstSrc *err_val_ptr = ir_build_unwrap_err_code_src(ag, scope, node, err_union_ptr);
IrInstSrc *err_val = ir_build_load_ptr(ag, scope, node, err_val_ptr);
ir_mark_gen(ir_build_add_implicit_return_type(ag, scope, node, err_val, nullptr));
ir_build_add_implicit_return_type(ag, scope, node, err_val, nullptr);
IrInstSrcSpillBegin *spill_begin = ir_build_spill_begin_src(ag, scope, node, err_val,
SpillIdRetErrCode);
ResultLocReturn *result_loc_ret = heap::c_allocator.create<ResultLocReturn>();
@ -3173,7 +3169,7 @@ ZigVar *create_local_var(CodeGen *codegen, AstNode *node, Scope *parent_scope,
if (existing_var->var_type == nullptr || !type_is_invalid(existing_var->var_type)) {
ErrorMsg *msg = add_node_error(codegen, node,
buf_sprintf("redeclaration of variable '%s'", buf_ptr(name)));
add_error_note(codegen, msg, existing_var->decl_node, buf_sprintf("previous declaration is here"));
add_error_note(codegen, msg, existing_var->decl_node, buf_sprintf("previous declaration here"));
}
variable_entry->var_type = codegen->builtin_types.entry_invalid;
} else {
@ -3195,7 +3191,7 @@ ZigVar *create_local_var(CodeGen *codegen, AstNode *node, Scope *parent_scope,
if (want_err_msg) {
ErrorMsg *msg = add_node_error(codegen, node,
buf_sprintf("redefinition of '%s'", buf_ptr(name)));
add_error_note(codegen, msg, tld->source_node, buf_sprintf("previous definition is here"));
add_error_note(codegen, msg, tld->source_node, buf_sprintf("previous definition here"));
}
variable_entry->var_type = codegen->builtin_types.entry_invalid;
}
@ -3251,7 +3247,7 @@ static bool is_duplicate_label(CodeGen *g, Scope *scope, AstNode *node, Buf *nam
Buf *this_block_name = scope->id == ScopeIdBlock ? ((ScopeBlock *)scope)->name : ((ScopeLoop *)scope)->name;
if (this_block_name != nullptr && buf_eql_buf(name, this_block_name)) {
ErrorMsg *msg = add_node_error(g, node, buf_sprintf("redeclaration of label '%s'", buf_ptr(name)));
add_error_note(g, msg, scope->source_node, buf_sprintf("previous declaration is here"));
add_error_note(g, msg, scope->source_node, buf_sprintf("previous declaration here"));
return true;
}
}
@ -3338,7 +3334,7 @@ static IrInstSrc *astgen_block(Stage1AstGen *ag, Scope *parent_scope, AstNode *b
child_scope = decl_var_instruction->var->child_scope;
} else if (!is_continuation_unreachable) {
// this statement's value must be void
ir_mark_gen(ir_build_check_statement_is_void(ag, child_scope, statement_node, statement_value));
ir_build_check_statement_is_void(ag, child_scope, statement_node, statement_value);
}
}
@ -3364,7 +3360,7 @@ static IrInstSrc *astgen_block(Stage1AstGen *ag, Scope *parent_scope, AstNode *b
return ir_expr_wrap(ag, parent_scope, phi, result_loc);
} else {
incoming_blocks.append(ag->current_basic_block);
IrInstSrc *else_expr_result = ir_mark_gen(ir_build_const_void(ag, parent_scope, block_node));
IrInstSrc *else_expr_result = ir_build_const_void(ag, parent_scope, block_node);
if (scope_block->peer_parent != nullptr) {
ResultLocPeer *peer_result = create_peer_result(scope_block->peer_parent);
@ -3387,13 +3383,13 @@ static IrInstSrc *astgen_block(Stage1AstGen *ag, Scope *parent_scope, AstNode *b
IrInstSrc *result;
if (block_node->data.block.name != nullptr) {
ir_mark_gen(ir_build_br(ag, parent_scope, block_node, scope_block->end_block, scope_block->is_comptime));
ir_build_br(ag, parent_scope, block_node, scope_block->end_block, scope_block->is_comptime);
ir_set_cursor_at_end_and_append_block(ag, scope_block->end_block);
IrInstSrc *phi = ir_build_phi(ag, parent_scope, block_node, incoming_blocks.length,
incoming_blocks.items, incoming_values.items, scope_block->peer_parent);
result = ir_expr_wrap(ag, parent_scope, phi, result_loc);
} else {
IrInstSrc *void_inst = ir_mark_gen(ir_build_const_void(ag, child_scope, block_node));
IrInstSrc *void_inst = ir_build_const_void(ag, child_scope, block_node);
result = ir_lval_wrap(ag, parent_scope, void_inst, lval, result_loc);
}
if (!is_return_from_fn)
@ -3402,14 +3398,14 @@ static IrInstSrc *astgen_block(Stage1AstGen *ag, Scope *parent_scope, AstNode *b
// no need for save_err_ret_addr because this cannot return error
// only generate unconditional defers
ir_mark_gen(ir_build_add_implicit_return_type(ag, child_scope, block_node, result, nullptr));
ir_build_add_implicit_return_type(ag, child_scope, block_node, result, nullptr);
ResultLocReturn *result_loc_ret = heap::c_allocator.create<ResultLocReturn>();
result_loc_ret->base.id = ResultLocIdReturn;
ir_build_reset_result(ag, parent_scope, block_node, &result_loc_ret->base);
ir_mark_gen(ir_build_end_expr(ag, parent_scope, block_node, result, &result_loc_ret->base));
ir_build_end_expr(ag, parent_scope, block_node, result, &result_loc_ret->base);
if (!astgen_defers_for_block(ag, child_scope, outer_block_scope, nullptr, nullptr))
return ag->codegen->invalid_inst_src;
return ir_mark_gen(ir_build_return_src(ag, child_scope, result->base.source_node, result));
return ir_build_return_src(ag, child_scope, result->base.source_node, result);
}
static IrInstSrc *astgen_bin_op_id(Stage1AstGen *ag, Scope *scope, AstNode *node, IrBinOp op_id) {
@ -3628,7 +3624,7 @@ static IrInstSrc *astgen_orelse(Stage1AstGen *ag, Scope *parent_scope, AstNode *
return ag->codegen->invalid_inst_src;
Stage1ZirBasicBlock *after_null_block = ag->current_basic_block;
if (!instr_is_unreachable(null_result))
ir_mark_gen(ir_build_br(ag, parent_scope, node, end_block, is_comptime));
ir_build_br(ag, parent_scope, node, end_block, is_comptime);
ir_set_cursor_at_end_and_append_block(ag, ok_block);
IrInstSrc *unwrapped_ptr = ir_build_optional_unwrap_ptr(ag, parent_scope, node, maybe_ptr, false);
@ -5395,7 +5391,7 @@ static IrInstSrc *astgen_if_bool_expr(Stage1AstGen *ag, Scope *scope, AstNode *n
return ag->codegen->invalid_inst_src;
Stage1ZirBasicBlock *after_then_block = ag->current_basic_block;
if (!instr_is_unreachable(then_expr_result))
ir_mark_gen(ir_build_br(ag, scope, node, endif_block, is_comptime));
ir_build_br(ag, scope, node, endif_block, is_comptime);
ir_set_cursor_at_end_and_append_block(ag, else_block);
IrInstSrc *else_expr_result;
@ -5409,7 +5405,7 @@ static IrInstSrc *astgen_if_bool_expr(Stage1AstGen *ag, Scope *scope, AstNode *n
}
Stage1ZirBasicBlock *after_else_block = ag->current_basic_block;
if (!instr_is_unreachable(else_expr_result))
ir_mark_gen(ir_build_br(ag, scope, node, endif_block, is_comptime));
ir_build_br(ag, scope, node, endif_block, is_comptime);
ir_set_cursor_at_end_and_append_block(ag, endif_block);
IrInstSrc **incoming_values = heap::c_allocator.allocate<IrInstSrc *>(2);
@ -5954,12 +5950,11 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
IrInstSrc *is_err = ir_build_test_err_src(ag, scope, node->data.while_expr.condition, err_val_ptr,
true, false);
Stage1ZirBasicBlock *after_cond_block = ag->current_basic_block;
IrInstSrc *void_else_result = else_node ? nullptr : ir_mark_gen(ir_build_const_void(ag, scope, node));
IrInstSrc *void_else_result = else_node ? nullptr : ir_build_const_void(ag, scope, node);
IrInstSrc *cond_br_inst;
if (!instr_is_unreachable(is_err)) {
cond_br_inst = ir_build_cond_br(ag, scope, node->data.while_expr.condition, is_err,
else_block, body_block, is_comptime);
cond_br_inst->is_gen = true;
} else {
// for the purposes of the source instruction to ir_build_result_peers
cond_br_inst = ag->current_basic_block->instruction_list.last();
@ -6005,8 +6000,8 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
}
if (!instr_is_unreachable(body_result)) {
ir_mark_gen(ir_build_check_statement_is_void(ag, payload_scope, node->data.while_expr.body, body_result));
ir_mark_gen(ir_build_br(ag, payload_scope, node, continue_block, is_comptime));
ir_build_check_statement_is_void(ag, payload_scope, node->data.while_expr.body, body_result);
ir_build_br(ag, payload_scope, node, continue_block, is_comptime);
}
if (continue_expr_node) {
@ -6015,8 +6010,8 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
if (expr_result == ag->codegen->invalid_inst_src)
return expr_result;
if (!instr_is_unreachable(expr_result)) {
ir_mark_gen(ir_build_check_statement_is_void(ag, payload_scope, continue_expr_node, expr_result));
ir_mark_gen(ir_build_br(ag, payload_scope, node, cond_block, is_comptime));
ir_build_check_statement_is_void(ag, payload_scope, continue_expr_node, expr_result);
ir_build_br(ag, payload_scope, node, cond_block, is_comptime);
}
}
@ -6041,7 +6036,7 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
if (else_result == ag->codegen->invalid_inst_src)
return else_result;
if (!instr_is_unreachable(else_result))
ir_mark_gen(ir_build_br(ag, scope, node, end_block, is_comptime));
ir_build_br(ag, scope, node, end_block, is_comptime);
Stage1ZirBasicBlock *after_else_block = ag->current_basic_block;
ir_set_cursor_at_end_and_append_block(ag, end_block);
if (else_result) {
@ -6075,12 +6070,11 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
IrInstSrc *maybe_val = ir_build_load_ptr(ag, scope, node->data.while_expr.condition, maybe_val_ptr);
IrInstSrc *is_non_null = ir_build_test_non_null_src(ag, scope, node->data.while_expr.condition, maybe_val);
Stage1ZirBasicBlock *after_cond_block = ag->current_basic_block;
IrInstSrc *void_else_result = else_node ? nullptr : ir_mark_gen(ir_build_const_void(ag, scope, node));
IrInstSrc *void_else_result = else_node ? nullptr : ir_build_const_void(ag, scope, node);
IrInstSrc *cond_br_inst;
if (!instr_is_unreachable(is_non_null)) {
cond_br_inst = ir_build_cond_br(ag, scope, node->data.while_expr.condition, is_non_null,
body_block, else_block, is_comptime);
cond_br_inst->is_gen = true;
} else {
// for the purposes of the source instruction to ir_build_result_peers
cond_br_inst = ag->current_basic_block->instruction_list.last();
@ -6123,8 +6117,8 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
}
if (!instr_is_unreachable(body_result)) {
ir_mark_gen(ir_build_check_statement_is_void(ag, child_scope, node->data.while_expr.body, body_result));
ir_mark_gen(ir_build_br(ag, child_scope, node, continue_block, is_comptime));
ir_build_check_statement_is_void(ag, child_scope, node->data.while_expr.body, body_result);
ir_build_br(ag, child_scope, node, continue_block, is_comptime);
}
if (continue_expr_node) {
@ -6133,8 +6127,8 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
if (expr_result == ag->codegen->invalid_inst_src)
return expr_result;
if (!instr_is_unreachable(expr_result)) {
ir_mark_gen(ir_build_check_statement_is_void(ag, child_scope, continue_expr_node, expr_result));
ir_mark_gen(ir_build_br(ag, child_scope, node, cond_block, is_comptime));
ir_build_check_statement_is_void(ag, child_scope, continue_expr_node, expr_result);
ir_build_br(ag, child_scope, node, cond_block, is_comptime);
}
}
@ -6151,7 +6145,7 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
if (else_result == ag->codegen->invalid_inst_src)
return else_result;
if (!instr_is_unreachable(else_result))
ir_mark_gen(ir_build_br(ag, scope, node, end_block, is_comptime));
ir_build_br(ag, scope, node, end_block, is_comptime);
}
Stage1ZirBasicBlock *after_else_block = ag->current_basic_block;
ir_set_cursor_at_end_and_append_block(ag, end_block);
@ -6175,12 +6169,11 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
if (cond_val == ag->codegen->invalid_inst_src)
return cond_val;
Stage1ZirBasicBlock *after_cond_block = ag->current_basic_block;
IrInstSrc *void_else_result = else_node ? nullptr : ir_mark_gen(ir_build_const_void(ag, scope, node));
IrInstSrc *void_else_result = else_node ? nullptr : ir_build_const_void(ag, scope, node);
IrInstSrc *cond_br_inst;
if (!instr_is_unreachable(cond_val)) {
cond_br_inst = ir_build_cond_br(ag, scope, node->data.while_expr.condition, cond_val,
body_block, else_block, is_comptime);
cond_br_inst->is_gen = true;
} else {
// for the purposes of the source instruction to ir_build_result_peers
cond_br_inst = ag->current_basic_block->instruction_list.last();
@ -6219,8 +6212,8 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
}
if (!instr_is_unreachable(body_result)) {
ir_mark_gen(ir_build_check_statement_is_void(ag, scope, node->data.while_expr.body, body_result));
ir_mark_gen(ir_build_br(ag, scope, node, continue_block, is_comptime));
ir_build_check_statement_is_void(ag, scope, node->data.while_expr.body, body_result);
ir_build_br(ag, scope, node, continue_block, is_comptime);
}
if (continue_expr_node) {
@ -6229,8 +6222,8 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
if (expr_result == ag->codegen->invalid_inst_src)
return expr_result;
if (!instr_is_unreachable(expr_result)) {
ir_mark_gen(ir_build_check_statement_is_void(ag, scope, continue_expr_node, expr_result));
ir_mark_gen(ir_build_br(ag, scope, node, cond_block, is_comptime));
ir_build_check_statement_is_void(ag, scope, continue_expr_node, expr_result);
ir_build_br(ag, scope, node, cond_block, is_comptime);
}
}
@ -6248,7 +6241,7 @@ static IrInstSrc *astgen_while_expr(Stage1AstGen *ag, Scope *scope, AstNode *nod
if (else_result == ag->codegen->invalid_inst_src)
return else_result;
if (!instr_is_unreachable(else_result))
ir_mark_gen(ir_build_br(ag, scope, node, end_block, is_comptime));
ir_build_br(ag, scope, node, end_block, is_comptime);
}
Stage1ZirBasicBlock *after_else_block = ag->current_basic_block;
ir_set_cursor_at_end_and_append_block(ag, end_block);
@ -6332,9 +6325,9 @@ static IrInstSrc *astgen_for_expr(Stage1AstGen *ag, Scope *parent_scope, AstNode
IrInstSrc *index_val = ir_build_load_ptr(ag, &spill_scope->base, node, index_ptr);
IrInstSrc *cond = ir_build_bin_op(ag, parent_scope, node, IrBinOpCmpLessThan, index_val, len_val, false);
Stage1ZirBasicBlock *after_cond_block = ag->current_basic_block;
IrInstSrc *void_else_value = else_node ? nullptr : ir_mark_gen(ir_build_const_void(ag, parent_scope, node));
IrInstSrc *cond_br_inst = ir_mark_gen(ir_build_cond_br(ag, parent_scope, node, cond,
body_block, else_block, is_comptime));
IrInstSrc *void_else_value = else_node ? nullptr : ir_build_const_void(ag, parent_scope, node);
IrInstSrc *cond_br_inst = ir_build_cond_br(ag, parent_scope, node, cond,
body_block, else_block, is_comptime);
ResultLocPeerParent *peer_parent = ir_build_result_peers(ag, cond_br_inst, end_block, result_loc, is_comptime);
@ -6377,8 +6370,8 @@ static IrInstSrc *astgen_for_expr(Stage1AstGen *ag, Scope *parent_scope, AstNode
}
if (!instr_is_unreachable(body_result)) {
ir_mark_gen(ir_build_check_statement_is_void(ag, child_scope, node->data.for_expr.body, body_result));
ir_mark_gen(ir_build_br(ag, child_scope, node, continue_block, is_comptime));
ir_build_check_statement_is_void(ag, child_scope, node->data.for_expr.body, body_result);
ir_build_br(ag, child_scope, node, continue_block, is_comptime);
}
ir_set_cursor_at_end_and_append_block(ag, continue_block);
@ -6399,7 +6392,7 @@ static IrInstSrc *astgen_for_expr(Stage1AstGen *ag, Scope *parent_scope, AstNode
if (else_result == ag->codegen->invalid_inst_src)
return else_result;
if (!instr_is_unreachable(else_result))
ir_mark_gen(ir_build_br(ag, parent_scope, node, end_block, is_comptime));
ir_build_br(ag, parent_scope, node, end_block, is_comptime);
}
Stage1ZirBasicBlock *after_else_block = ag->current_basic_block;
ir_set_cursor_at_end_and_append_block(ag, end_block);
@ -6719,7 +6712,7 @@ static IrInstSrc *astgen_if_optional_expr(Stage1AstGen *ag, Scope *scope, AstNod
return then_expr_result;
Stage1ZirBasicBlock *after_then_block = ag->current_basic_block;
if (!instr_is_unreachable(then_expr_result))
ir_mark_gen(ir_build_br(ag, scope, node, endif_block, is_comptime));
ir_build_br(ag, scope, node, endif_block, is_comptime);
ir_set_cursor_at_end_and_append_block(ag, else_block);
IrInstSrc *else_expr_result;
@ -6733,7 +6726,7 @@ static IrInstSrc *astgen_if_optional_expr(Stage1AstGen *ag, Scope *scope, AstNod
}
Stage1ZirBasicBlock *after_else_block = ag->current_basic_block;
if (!instr_is_unreachable(else_expr_result))
ir_mark_gen(ir_build_br(ag, scope, node, endif_block, is_comptime));
ir_build_br(ag, scope, node, endif_block, is_comptime);
ir_set_cursor_at_end_and_append_block(ag, endif_block);
IrInstSrc **incoming_values = heap::c_allocator.allocate<IrInstSrc *>(2);
@ -6802,7 +6795,7 @@ static IrInstSrc *astgen_if_err_expr(Stage1AstGen *ag, Scope *scope, AstNode *no
return then_expr_result;
Stage1ZirBasicBlock *after_then_block = ag->current_basic_block;
if (!instr_is_unreachable(then_expr_result))
ir_mark_gen(ir_build_br(ag, scope, node, endif_block, is_comptime));
ir_build_br(ag, scope, node, endif_block, is_comptime);
ir_set_cursor_at_end_and_append_block(ag, else_block);
@ -6831,7 +6824,7 @@ static IrInstSrc *astgen_if_err_expr(Stage1AstGen *ag, Scope *scope, AstNode *no
}
Stage1ZirBasicBlock *after_else_block = ag->current_basic_block;
if (!instr_is_unreachable(else_expr_result))
ir_mark_gen(ir_build_br(ag, scope, node, endif_block, is_comptime));
ir_build_br(ag, scope, node, endif_block, is_comptime);
ir_set_cursor_at_end_and_append_block(ag, endif_block);
IrInstSrc **incoming_values = heap::c_allocator.allocate<IrInstSrc *>(2);
@ -6893,7 +6886,7 @@ static bool astgen_switch_prong_expr(Stage1AstGen *ag, Scope *scope, AstNode *sw
if (expr_result == ag->codegen->invalid_inst_src)
return false;
if (!instr_is_unreachable(expr_result))
ir_mark_gen(ir_build_br(ag, scope, switch_node, end_block, is_comptime));
ir_build_br(ag, scope, switch_node, end_block, is_comptime);
incoming_blocks->append(ag->current_basic_block);
incoming_values->append(expr_result);
return true;
@ -7008,8 +7001,8 @@ static IrInstSrc *astgen_switch_expr(Stage1AstGen *ag, Scope *scope, AstNode *no
assert(ok_bit);
assert(last_item_node);
IrInstSrc *br_inst = ir_mark_gen(ir_build_cond_br(ag, scope, last_item_node, ok_bit,
range_block_yes, range_block_no, is_comptime));
IrInstSrc *br_inst = ir_build_cond_br(ag, scope, last_item_node, ok_bit,
range_block_yes, range_block_no, is_comptime);
if (peer_parent->base.source_instruction == nullptr) {
peer_parent->base.source_instruction = br_inst;
}
@ -7033,7 +7026,7 @@ static IrInstSrc *astgen_switch_expr(Stage1AstGen *ag, Scope *scope, AstNode *no
ErrorMsg *msg = add_node_error(ag->codegen, prong_node,
buf_sprintf("multiple else prongs in switch expression"));
add_error_note(ag->codegen, msg, else_prong,
buf_sprintf("previous else prong is here"));
buf_sprintf("previous else prong here"));
return ag->codegen->invalid_inst_src;
}
else_prong = prong_node;
@ -7044,7 +7037,7 @@ static IrInstSrc *astgen_switch_expr(Stage1AstGen *ag, Scope *scope, AstNode *no
ErrorMsg *msg = add_node_error(ag->codegen, prong_node,
buf_sprintf("multiple '_' prongs in switch expression"));
add_error_note(ag->codegen, msg, underscore_prong,
buf_sprintf("previous '_' prong is here"));
buf_sprintf("previous '_' prong here"));
return ag->codegen->invalid_inst_src;
}
underscore_prong = prong_node;
@ -7056,10 +7049,10 @@ static IrInstSrc *astgen_switch_expr(Stage1AstGen *ag, Scope *scope, AstNode *no
buf_sprintf("else and '_' prong in switch expression"));
if (underscore_prong == prong_node)
add_error_note(ag->codegen, msg, else_prong,
buf_sprintf("else prong is here"));
buf_sprintf("else prong here"));
else
add_error_note(ag->codegen, msg, underscore_prong,
buf_sprintf("'_' prong is here"));
buf_sprintf("'_' prong here"));
return ag->codegen->invalid_inst_src;
}
ResultLocPeer *this_peer_result_loc = create_peer_result(peer_parent);
@ -7349,14 +7342,14 @@ static IrInstSrc *astgen_continue(Stage1AstGen *ag, Scope *continue_scope, AstNo
for (size_t i = 0; i < runtime_scopes.length; i += 1) {
ScopeRuntime *scope_runtime = runtime_scopes.at(i);
ir_mark_gen(ir_build_check_runtime_scope(ag, continue_scope, node, scope_runtime->is_comptime, is_comptime));
ir_build_check_runtime_scope(ag, continue_scope, node, scope_runtime->is_comptime, is_comptime);
}
runtime_scopes.deinit();
Stage1ZirBasicBlock *dest_block = loop_scope->continue_block;
if (!astgen_defers_for_block(ag, continue_scope, dest_block->scope, nullptr, nullptr))
return ag->codegen->invalid_inst_src;
return ir_mark_gen(ir_build_br(ag, continue_scope, node, dest_block, is_comptime));
return ir_build_br(ag, continue_scope, node, dest_block, is_comptime);
}
static IrInstSrc *astgen_error_type(Stage1AstGen *ag, Scope *scope, AstNode *node) {
@ -7482,7 +7475,7 @@ static IrInstSrc *astgen_catch(Stage1AstGen *ag, Scope *parent_scope, AstNode *n
return ag->codegen->invalid_inst_src;
Stage1ZirBasicBlock *after_err_block = ag->current_basic_block;
if (!instr_is_unreachable(err_result))
ir_mark_gen(ir_build_br(ag, parent_scope, node, end_block, is_comptime));
ir_build_br(ag, parent_scope, node, end_block, is_comptime);
ir_set_cursor_at_end_and_append_block(ag, ok_block);
IrInstSrc *unwrapped_ptr = ir_build_unwrap_err_payload_src(ag, parent_scope, node, err_union_ptr, false, false);
@ -7757,9 +7750,9 @@ static IrInstSrc *astgen_suspend(Stage1AstGen *ag, Scope *parent_scope, AstNode
IrInstSrc *susp_res = astgen_node(ag, node->data.suspend.block, child_scope);
if (susp_res == ag->codegen->invalid_inst_src)
return ag->codegen->invalid_inst_src;
ir_mark_gen(ir_build_check_statement_is_void(ag, child_scope, node->data.suspend.block, susp_res));
ir_build_check_statement_is_void(ag, child_scope, node->data.suspend.block, susp_res);
return ir_mark_gen(ir_build_suspend_finish_src(ag, parent_scope, node, begin));
return ir_build_suspend_finish_src(ag, parent_scope, node, begin);
}
static IrInstSrc *astgen_node_raw(Stage1AstGen *ag, AstNode *node, Scope *scope,
@ -8073,13 +8066,13 @@ bool stage1_astgen(CodeGen *codegen, AstNode *node, Scope *scope, Stage1Zir *sta
}
if (!instr_is_unreachable(result)) {
ir_mark_gen(ir_build_add_implicit_return_type(ag, scope, result->base.source_node, result, nullptr));
ir_build_add_implicit_return_type(ag, scope, result->base.source_node, result, nullptr);
// no need for save_err_ret_addr because this cannot return error
ResultLocReturn *result_loc_ret = heap::c_allocator.create<ResultLocReturn>();
result_loc_ret->base.id = ResultLocIdReturn;
ir_build_reset_result(ag, scope, node, &result_loc_ret->base);
ir_mark_gen(ir_build_end_expr(ag, scope, node, result, &result_loc_ret->base));
ir_mark_gen(ir_build_return_src(ag, scope, result->base.source_node, result));
ir_build_end_expr(ag, scope, node, result, &result_loc_ret->base);
ir_build_return_src(ag, scope, result->base.source_node, result);
}
return true;

View File

@ -5407,16 +5407,6 @@ static void ir_finish_bb(IrAnalyze *ira) {
ira->new_irb.current_basic_block->debug_id);
}
}
ira->instruction_index += 1;
while (ira->instruction_index < ira->zir_current_basic_block->instruction_list.length) {
IrInstSrc *next_instruction = ira->zir_current_basic_block->instruction_list.at(ira->instruction_index);
if (!next_instruction->is_gen) {
ir_add_error(ira, &next_instruction->base, buf_sprintf("unreachable code"));
break;
}
ira->instruction_index += 1;
}
ir_start_next_bb(ira);
}
@ -11107,7 +11097,7 @@ static IrInstGen *ir_analyze_instruction_export(IrAnalyze *ira, IrInstSrcExport
AstNode *other_export_node = entry->value->source_node;
ErrorMsg *msg = ir_add_error(ira, &instruction->base.base,
buf_sprintf("exported symbol collision: '%s'", buf_ptr(symbol_name)));
add_error_note(ira->codegen, msg, other_export_node, buf_sprintf("other symbol is here"));
add_error_note(ira->codegen, msg, other_export_node, buf_sprintf("other symbol here"));
return ira->codegen->invalid_inst_gen;
}
@ -11413,7 +11403,7 @@ static IrInstGen *ir_analyze_instruction_extern(IrAnalyze *ira, IrInstSrcExtern
AstNode *other_extern_node = entry->value->source_node;
ErrorMsg *msg = ir_add_error(ira, &instruction->base.base,
buf_sprintf("extern symbol collision: '%s'", buf_ptr(symbol_name)));
add_error_note(ira->codegen, msg, other_extern_node, buf_sprintf("other symbol is here"));
add_error_note(ira->codegen, msg, other_extern_node, buf_sprintf("other symbol here"));
return ira->codegen->invalid_inst_gen;
}
@ -15934,7 +15924,7 @@ static IrInstGen *ir_analyze_instruction_pop_count(IrAnalyze *ira, IrInstSrcPopC
return ir_build_pop_count_gen(ira, &instruction->base.base, return_type, op);
}
static IrInstGen *ir_analyze_union_tag(IrAnalyze *ira, IrInst* source_instr, IrInstGen *value, bool is_gen) {
static IrInstGen *ir_analyze_union_tag(IrAnalyze *ira, IrInst* source_instr, IrInstGen *value) {
if (type_is_invalid(value->value->type))
return ira->codegen->invalid_inst_gen;
@ -15943,7 +15933,7 @@ static IrInstGen *ir_analyze_union_tag(IrAnalyze *ira, IrInst* source_instr, IrI
buf_sprintf("expected enum or union type, found '%s'", buf_ptr(&value->value->type->name)));
return ira->codegen->invalid_inst_gen;
}
if (!value->value->type->data.unionation.have_explicit_tag_type && !is_gen) {
if (!value->value->type->data.unionation.have_explicit_tag_type) {
ErrorMsg *msg = ir_add_error(ira, source_instr, buf_sprintf("union has no associated enum"));
if (value->value->type->data.unionation.decl_node != nullptr) {
add_error_note(ira->codegen, msg, value->value->type->data.unionation.decl_node,
@ -16906,7 +16896,7 @@ static IrInstGen *ir_analyze_instruction_enum_tag_name(IrAnalyze *ira, IrInstSrc
}
if (target_type->id == ZigTypeIdUnion) {
target = ir_analyze_union_tag(ira, &instruction->base.base, target, instruction->base.is_gen);
target = ir_analyze_union_tag(ira, &instruction->base.base, target);
if (type_is_invalid(target->value->type))
return ira->codegen->invalid_inst_gen;
target_type = target->value->type;
@ -21742,7 +21732,7 @@ static IrInstGen *ir_analyze_instruction_check_switch_prongs(IrAnalyze *ira,
ErrorMsg *msg = ir_add_error(ira, &start_value->base,
buf_sprintf("duplicate switch value: '%s.%s'", buf_ptr(&switch_type->name),
buf_ptr(enum_field->name)));
add_error_note(ira->codegen, msg, prev_node, buf_sprintf("other value is here"));
add_error_note(ira->codegen, msg, prev_node, buf_sprintf("other value here"));
}
bigint_incr(&field_index);
}
@ -21828,7 +21818,7 @@ static IrInstGen *ir_analyze_instruction_check_switch_prongs(IrAnalyze *ira,
Buf *err_name = &ira->codegen->errors_by_index.at(start_index)->name;
ErrorMsg *msg = ir_add_error(ira, &start_value->base,
buf_sprintf("duplicate switch value: '%s.%s'", buf_ptr(&switch_type->name), buf_ptr(err_name)));
add_error_note(ira->codegen, msg, prev_node, buf_sprintf("other value is here"));
add_error_note(ira->codegen, msg, prev_node, buf_sprintf("other value here"));
}
field_prev_uses[start_index] = start_value->base.source_node;
}
@ -21890,7 +21880,7 @@ static IrInstGen *ir_analyze_instruction_check_switch_prongs(IrAnalyze *ira,
start_value->base.source_node);
if (prev_node != nullptr) {
ErrorMsg *msg = ir_add_error(ira, &start_value->base, buf_sprintf("duplicate switch value"));
add_error_note(ira->codegen, msg, prev_node, buf_sprintf("previous value is here"));
add_error_note(ira->codegen, msg, prev_node, buf_sprintf("previous value here"));
return ira->codegen->invalid_inst_gen;
}
}
@ -21975,7 +21965,7 @@ static IrInstGen *ir_analyze_instruction_check_switch_prongs(IrAnalyze *ira,
auto entry = prevs.put_unique(const_expr_val->data.x_type, value);
if(entry != nullptr) {
ErrorMsg *msg = ir_add_error(ira, &value->base, buf_sprintf("duplicate switch value"));
add_error_note(ira->codegen, msg, entry->value->base.source_node, buf_sprintf("previous value is here"));
add_error_note(ira->codegen, msg, entry->value->base.source_node, buf_sprintf("previous value here"));
prevs.deinit();
return ira->codegen->invalid_inst_gen;
}

View File

@ -577,8 +577,6 @@ static void ir_print_prefix_src(IrPrintSrc *irp, IrInstSrc *instruction, bool tr
const char *type_name;
if (instruction->id == IrInstSrcIdConst) {
type_name = buf_ptr(&reinterpret_cast<IrInstSrcConst *>(instruction)->value->type->name);
} else if (instruction->is_noreturn) {
type_name = "noreturn";
} else {
type_name = "(unknown)";
}

View File

@ -170,6 +170,73 @@ pub fn hasValgrindSupport(target: std.Target) bool {
}
}
/// The set of targets that LLVM has non-experimental support for.
/// Used to select between LLVM backend and self-hosted backend when compiling in
/// release modes.
pub fn hasLlvmSupport(target: std.Target) bool {
return switch (target.cpu.arch) {
.arm,
.armeb,
.aarch64,
.aarch64_be,
.aarch64_32,
.arc,
.avr,
.bpfel,
.bpfeb,
.csky,
.hexagon,
.mips,
.mipsel,
.mips64,
.mips64el,
.msp430,
.powerpc,
.powerpcle,
.powerpc64,
.powerpc64le,
.r600,
.amdgcn,
.riscv32,
.riscv64,
.sparc,
.sparcv9,
.sparcel,
.s390x,
.tce,
.tcele,
.thumb,
.thumbeb,
.i386,
.x86_64,
.xcore,
.nvptx,
.nvptx64,
.le32,
.le64,
.amdil,
.amdil64,
.hsail,
.hsail64,
.spir,
.spir64,
.kalimba,
.shave,
.lanai,
.wasm32,
.wasm64,
.renderscript32,
.renderscript64,
.ve,
=> true,
.spu_2,
.spirv32,
.spirv64,
=> false,
};
}
pub fn supportsStackProbing(target: std.Target) bool {
return target.os.tag != .windows and target.os.tag != .uefi and
(target.cpu.arch == .i386 or target.cpu.arch == .x86_64);

View File

@ -10,18 +10,25 @@ const enable_wine: bool = build_options.enable_wine;
const enable_wasmtime: bool = build_options.enable_wasmtime;
const enable_darling: bool = build_options.enable_darling;
const glibc_multi_install_dir: ?[]const u8 = build_options.glibc_multi_install_dir;
const skip_compile_errors = build_options.skip_compile_errors;
const ThreadPool = @import("ThreadPool.zig");
const CrossTarget = std.zig.CrossTarget;
const print = std.debug.print;
const assert = std.debug.assert;
const zig_h = link.File.C.zig_h;
const hr = "=" ** 80;
test "self-hosted" {
test {
if (build_options.is_stage1) {
@import("stage1.zig").os_init();
}
var ctx = TestContext.init();
defer ctx.deinit();
try @import("stage2_tests").addCases(&ctx);
try @import("test_cases").addCases(&ctx);
try ctx.run();
}
@ -30,7 +37,11 @@ const ErrorMsg = union(enum) {
src: struct {
src_path: []const u8,
msg: []const u8,
// maxint means match anything
// this is a workaround for stage1 compiler bug I ran into when making it ?u32
line: u32,
// maxint means match anything
// this is a workaround for stage1 compiler bug I ran into when making it ?u32
column: u32,
kind: Kind,
},
@ -74,23 +85,32 @@ const ErrorMsg = union(enum) {
_ = options;
switch (self) {
.src => |src| {
return writer.print("{s}:{d}:{d}: {s}: {s}", .{
src.src_path,
src.line + 1,
src.column + 1,
@tagName(src.kind),
src.msg,
});
if (!std.mem.eql(u8, src.src_path, "?") or
src.line != std.math.maxInt(u32) or
src.column != std.math.maxInt(u32))
{
try writer.print("{s}:", .{src.src_path});
if (src.line != std.math.maxInt(u32)) {
try writer.print("{d}:", .{src.line + 1});
} else {
try writer.writeAll("?:");
}
if (src.column != std.math.maxInt(u32)) {
try writer.print("{d}: ", .{src.column + 1});
} else {
try writer.writeAll("?: ");
}
}
return writer.print("{s}: {s}", .{ @tagName(src.kind), src.msg });
},
.plain => |plain| {
return writer.print("{s}: {s}", .{ plain.msg, @tagName(plain.kind) });
return writer.print("{s}: {s}", .{ @tagName(plain.kind), plain.msg });
},
}
}
};
pub const TestContext = struct {
/// TODO: find a way to treat cases as individual tests (shouldn't show "1 test passed" if there are 200 cases)
cases: std.ArrayList(Case),
pub const Update = struct {
@ -127,6 +147,12 @@ pub const TestContext = struct {
path: []const u8,
};
pub const Backend = enum {
stage1,
stage2,
llvm,
};
/// A `Case` consists of a list of `Update`. The same `Compilation` is used for each
/// update, so each update's source is treated as a single file being
/// updated by the test harness and incrementally compiled.
@ -140,13 +166,20 @@ pub const TestContext = struct {
/// In order to be able to run e.g. Execution updates, this must be set
/// to Executable.
output_mode: std.builtin.OutputMode,
optimize_mode: std.builtin.Mode = .Debug,
updates: std.ArrayList(Update),
object_format: ?std.Target.ObjectFormat = null,
emit_h: bool = false,
llvm_backend: bool = false,
is_test: bool = false,
expect_exact: bool = false,
backend: Backend = .stage2,
files: std.ArrayList(File),
pub fn addSourceFile(case: *Case, name: []const u8, src: [:0]const u8) void {
case.files.append(.{ .path = name, .src = src }) catch @panic("out of memory");
}
/// Adds a subcase in which the module is updated with `src`, and a C
/// header is generated.
pub fn addHeader(self: *Case, src: [:0]const u8, result: [:0]const u8) void {
@ -201,8 +234,14 @@ pub const TestContext = struct {
const kind_text = it.next() orelse @panic("missing 'error'/'note'");
const msg = it.rest()[1..]; // skip over the space at end of "error: "
const line = std.fmt.parseInt(u32, line_text, 10) catch @panic("bad line number");
const column = std.fmt.parseInt(u32, col_text, 10) catch @panic("bad column number");
const line: ?u32 = if (std.mem.eql(u8, line_text, "?"))
null
else
std.fmt.parseInt(u32, line_text, 10) catch @panic("bad line number");
const column: ?u32 = if (std.mem.eql(u8, line_text, "?"))
null
else
std.fmt.parseInt(u32, col_text, 10) catch @panic("bad column number");
const kind: ErrorMsg.Kind = if (std.mem.eql(u8, kind_text, " error"))
.@"error"
else if (std.mem.eql(u8, kind_text, " note"))
@ -210,16 +249,28 @@ pub const TestContext = struct {
else
@panic("expected 'error'/'note'");
if (line == 0 or column == 0) {
@panic("line and column must be specified starting at one");
}
const line_0based: u32 = if (line) |n| blk: {
if (n == 0) {
print("{s}: line must be specified starting at one\n", .{self.name});
return;
}
break :blk n - 1;
} else std.math.maxInt(u32);
const column_0based: u32 = if (column) |n| blk: {
if (n == 0) {
print("{s}: line must be specified starting at one\n", .{self.name});
return;
}
break :blk n - 1;
} else std.math.maxInt(u32);
array[i] = .{
.src = .{
.src_path = src_path,
.msg = msg,
.line = line - 1,
.column = column - 1,
.line = line_0based,
.column = column_0based,
.kind = kind,
},
};
@ -254,11 +305,6 @@ pub const TestContext = struct {
return ctx.addExe(name, target);
}
/// Adds a test case for ZIR input, producing an executable
pub fn exeZIR(ctx: *TestContext, name: []const u8, target: CrossTarget) *Case {
return ctx.addExe(name, target, .ZIR);
}
pub fn exeFromCompiledC(ctx: *TestContext, name: []const u8, target: CrossTarget) *Case {
const prefixed_name = std.fmt.allocPrint(ctx.cases.allocator, "CBE: {s}", .{name}) catch
@panic("out of memory");
@ -282,7 +328,7 @@ pub const TestContext = struct {
.updates = std.ArrayList(Update).init(ctx.cases.allocator),
.output_mode = .Exe,
.files = std.ArrayList(File).init(ctx.cases.allocator),
.llvm_backend = true,
.backend = .llvm,
}) catch @panic("out of memory");
return &ctx.cases.items[ctx.cases.items.len - 1];
}
@ -302,6 +348,22 @@ pub const TestContext = struct {
return &ctx.cases.items[ctx.cases.items.len - 1];
}
pub fn addTest(
ctx: *TestContext,
name: []const u8,
target: CrossTarget,
) *Case {
ctx.cases.append(Case{
.name = name,
.target = target,
.updates = std.ArrayList(Update).init(ctx.cases.allocator),
.output_mode = .Exe,
.is_test = true,
.files = std.ArrayList(File).init(ctx.cases.allocator),
}) catch @panic("out of memory");
return &ctx.cases.items[ctx.cases.items.len - 1];
}
/// Adds a test case for Zig input, producing an object file.
pub fn obj(ctx: *TestContext, name: []const u8, target: CrossTarget) *Case {
return ctx.addObj(name, target);
@ -333,6 +395,45 @@ pub const TestContext = struct {
ctx.addC(name, target).addHeader(src, zig_h ++ out);
}
pub fn objErrStage1(
ctx: *TestContext,
name: []const u8,
src: [:0]const u8,
expected_errors: []const []const u8,
) void {
if (skip_compile_errors) return;
const case = ctx.addObj(name, .{});
case.backend = .stage1;
case.addError(src, expected_errors);
}
pub fn testErrStage1(
ctx: *TestContext,
name: []const u8,
src: [:0]const u8,
expected_errors: []const []const u8,
) void {
if (skip_compile_errors) return;
const case = ctx.addTest(name, .{});
case.backend = .stage1;
case.addError(src, expected_errors);
}
pub fn exeErrStage1(
ctx: *TestContext,
name: []const u8,
src: [:0]const u8,
expected_errors: []const []const u8,
) void {
if (skip_compile_errors) return;
const case = ctx.addExe(name, .{});
case.backend = .stage1;
case.addError(src, expected_errors);
}
pub fn addCompareOutput(
ctx: *TestContext,
name: []const u8,
@ -386,18 +487,6 @@ pub const TestContext = struct {
ctx.addTransform(name, target, src, result);
}
/// Adds a test case that cleans up the ZIR source given in `src`, and
/// tests the resulting ZIR against `result`
pub fn transformZIR(
ctx: *TestContext,
name: []const u8,
target: CrossTarget,
src: [:0]const u8,
result: [:0]const u8,
) void {
ctx.addTransform(name, target, .ZIR, src, result);
}
pub fn addError(
ctx: *TestContext,
name: []const u8,
@ -555,7 +644,7 @@ pub const TestContext = struct {
continue;
// Skip tests that require LLVM backend when it is not available
if (!build_options.have_llvm and case.llvm_backend)
if (!build_options.have_llvm and case.backend == .llvm)
continue;
var prg_node = root_node.start(case.name, case.updates.items.len);
@ -567,7 +656,7 @@ pub const TestContext = struct {
progress.initial_delay_ns = 0;
progress.refresh_rate_ns = 0;
self.runOneCase(
runOneCase(
std.testing.allocator,
&prg_node,
case,
@ -576,17 +665,16 @@ pub const TestContext = struct {
global_cache_directory,
) catch |err| {
fail_count += 1;
std.debug.print("test '{s}' failed: {s}\n\n", .{ case.name, @errorName(err) });
print("test '{s}' failed: {s}\n\n", .{ case.name, @errorName(err) });
};
}
if (fail_count != 0) {
std.debug.print("{d} tests failed\n", .{fail_count});
print("{d} tests failed\n", .{fail_count});
return error.TestFailed;
}
}
fn runOneCase(
self: *TestContext,
allocator: *Allocator,
root_node: *std.Progress.Node,
case: Case,
@ -594,7 +682,6 @@ pub const TestContext = struct {
thread_pool: *ThreadPool,
global_cache_directory: Compilation.Directory,
) !void {
_ = self;
const target_info = try std.zig.system.NativeTargetInfo.detect(allocator, case.target);
const target = target_info.target;
@ -607,14 +694,155 @@ pub const TestContext = struct {
var cache_dir = try tmp.dir.makeOpenPath("zig-cache", .{});
defer cache_dir.close();
const tmp_dir_path = try std.fs.path.join(arena, &[_][]const u8{ ".", "zig-cache", "tmp", &tmp.sub_path });
const tmp_dir_path = try std.fs.path.join(
arena,
&[_][]const u8{ ".", "zig-cache", "tmp", &tmp.sub_path },
);
const tmp_dir_path_plus_slash = try std.fmt.allocPrint(
arena,
"{s}" ++ std.fs.path.sep_str,
.{tmp_dir_path},
);
const local_cache_path = try std.fs.path.join(
arena,
&[_][]const u8{ tmp_dir_path, "zig-cache" },
);
for (case.files.items) |file| {
try tmp.dir.writeFile(file.path, file.src);
}
if (case.backend == .stage1) {
// stage1 backend has limitations:
// * leaks memory
// * calls exit() when a compile error happens
// * cannot handle updates
// because of this we must spawn a child process rather than
// using Compilation directly.
assert(case.updates.items.len == 1);
const update = case.updates.items[0];
try tmp.dir.writeFile(tmp_src_path, update.src);
var zig_args = std.ArrayList([]const u8).init(arena);
try zig_args.append(std.testing.zig_exe_path);
if (case.is_test) {
try zig_args.append("test");
} else switch (case.output_mode) {
.Obj => try zig_args.append("build-obj"),
.Exe => try zig_args.append("build-exe"),
.Lib => try zig_args.append("build-lib"),
}
try zig_args.append(try std.fs.path.join(arena, &.{ tmp_dir_path, tmp_src_path }));
try zig_args.append("--name");
try zig_args.append("test");
try zig_args.append("--cache-dir");
try zig_args.append(local_cache_path);
try zig_args.append("--global-cache-dir");
try zig_args.append(global_cache_directory.path orelse ".");
if (!case.target.isNative()) {
try zig_args.append("-target");
try zig_args.append(try target.zigTriple(arena));
}
try zig_args.append("-O");
try zig_args.append(@tagName(case.optimize_mode));
const result = try std.ChildProcess.exec(.{
.allocator = arena,
.argv = zig_args.items,
});
switch (update.case) {
.Error => |case_error_list| {
switch (result.term) {
.Exited => |code| {
if (code == 0) {
dumpArgs(zig_args.items);
return error.CompilationIncorrectlySucceeded;
}
},
else => {
dumpArgs(zig_args.items);
return error.CompilationCrashed;
},
}
var ok = true;
if (case.expect_exact) {
var err_iter = std.mem.split(result.stderr, "\n");
var i: usize = 0;
ok = while (err_iter.next()) |line| : (i += 1) {
if (i >= case_error_list.len) break false;
const expected = try std.mem.replaceOwned(
u8,
arena,
try std.fmt.allocPrint(arena, "{s}", .{case_error_list[i]}),
"${DIR}",
tmp_dir_path_plus_slash,
);
if (std.mem.indexOf(u8, line, expected) == null) break false;
continue;
} else true;
ok = ok and i == case_error_list.len;
if (!ok) {
print("\n======== Expected these compile errors: ========\n", .{});
for (case_error_list) |msg| {
const expected = try std.fmt.allocPrint(arena, "{s}", .{msg});
print("{s}\n", .{expected});
}
}
} else {
for (case_error_list) |msg| {
const expected = try std.mem.replaceOwned(
u8,
arena,
try std.fmt.allocPrint(arena, "{s}", .{msg}),
"${DIR}",
tmp_dir_path_plus_slash,
);
if (std.mem.indexOf(u8, result.stderr, expected) == null) {
print(
\\
\\=========== Expected compile error: ============
\\{s}
\\
, .{expected});
ok = false;
break;
}
}
}
if (!ok) {
print(
\\================= Full output: =================
\\{s}
\\================================================
\\
, .{result.stderr});
return error.TestFailed;
}
},
.CompareObjectFile => @panic("TODO implement in the test harness"),
.Execution => @panic("TODO implement in the test harness"),
.Header => @panic("TODO implement in the test harness"),
}
return;
}
const zig_cache_directory: Compilation.Directory = .{
.handle = cache_dir,
.path = try std.fs.path.join(arena, &[_][]const u8{ tmp_dir_path, "zig-cache" }),
.path = local_cache_path,
};
const tmp_src_path = "test_case.zig";
var root_pkg: Package = .{
.root_src_directory = .{ .path = tmp_dir_path, .handle = tmp.dir },
.root_src_path = tmp_src_path,
@ -640,6 +868,14 @@ pub const TestContext = struct {
.directory = emit_directory,
.basename = "test_case.h",
} else null;
const use_llvm: ?bool = switch (case.backend) {
.llvm => true,
else => null,
};
const use_stage1: ?bool = switch (case.backend) {
.stage1 => true,
else => null,
};
const comp = try Compilation.create(allocator, .{
.local_cache_directory = zig_cache_directory,
.global_cache_directory = global_cache_directory,
@ -651,8 +887,8 @@ pub const TestContext = struct {
// and linking. This will require a rework to support multi-file
// tests.
.output_mode = case.output_mode,
// TODO: support testing optimizations
.optimize_mode = .Debug,
.is_test = case.is_test,
.optimize_mode = case.optimize_mode,
.emit_bin = emit_bin,
.emit_h = emit_h,
.root_pkg = &root_pkg,
@ -661,17 +897,13 @@ pub const TestContext = struct {
.is_native_os = case.target.isNativeOs(),
.is_native_abi = case.target.isNativeAbi(),
.dynamic_linker = target_info.dynamic_linker.get(),
.link_libc = case.llvm_backend,
.use_llvm = case.llvm_backend,
.use_lld = case.llvm_backend,
.link_libc = case.backend == .llvm,
.use_llvm = use_llvm,
.use_stage1 = use_stage1,
.self_exe_path = std.testing.zig_exe_path,
});
defer comp.destroy();
for (case.files.items) |file| {
try tmp.dir.writeFile(file.path, file.src);
}
for (case.updates.items) |update, update_index| {
var update_node = root_node.start("update", 3);
update_node.activate();
@ -692,19 +924,19 @@ pub const TestContext = struct {
var all_errors = try comp.getAllErrorsAlloc();
defer all_errors.deinit(allocator);
if (all_errors.list.len != 0) {
std.debug.print(
print(
"\nCase '{s}': unexpected errors at update_index={d}:\n{s}\n",
.{ case.name, update_index, hr },
);
for (all_errors.list) |err_msg| {
switch (err_msg) {
.src => |src| {
std.debug.print("{s}:{d}:{d}: error: {s}\n{s}\n", .{
print("{s}:{d}:{d}: error: {s}\n{s}\n", .{
src.src_path, src.line + 1, src.column + 1, src.msg, hr,
});
},
.plain => |plain| {
std.debug.print("error: {s}\n{s}\n", .{ plain.msg, hr });
print("error: {s}\n{s}\n", .{ plain.msg, hr });
},
}
}
@ -757,10 +989,20 @@ pub const TestContext = struct {
const src_path_ok = case_msg.src.src_path.len == 0 or
std.mem.eql(u8, case_msg.src.src_path, actual_msg.src_path);
const expected_msg = try std.mem.replaceOwned(
u8,
arena,
case_msg.src.msg,
"${DIR}",
tmp_dir_path_plus_slash,
);
if (src_path_ok and
actual_msg.line == case_msg.src.line and
actual_msg.column == case_msg.src.column and
std.mem.eql(u8, case_msg.src.msg, actual_msg.msg) and
(case_msg.src.line == std.math.maxInt(u32) or
actual_msg.line == case_msg.src.line) and
(case_msg.src.column == std.math.maxInt(u32) or
actual_msg.column == case_msg.src.column) and
std.mem.eql(u8, expected_msg, actual_msg.msg) and
case_msg.src.kind == .@"error")
{
handled_errors[i] = true;
@ -779,7 +1021,7 @@ pub const TestContext = struct {
},
}
} else {
std.debug.print(
print(
"\nUnexpected error:\n{s}\n{}\n{s}",
.{ hr, ErrorMsg.init(actual_error, .@"error"), hr },
);
@ -796,9 +1038,19 @@ pub const TestContext = struct {
}
if (ex_tag != .src) continue;
if (actual_msg.line == case_msg.src.line and
actual_msg.column == case_msg.src.column and
std.mem.eql(u8, case_msg.src.msg, actual_msg.msg) and
const expected_msg = try std.mem.replaceOwned(
u8,
arena,
case_msg.src.msg,
"${DIR}",
tmp_dir_path_plus_slash,
);
if ((case_msg.src.line == std.math.maxInt(u32) or
actual_msg.line == case_msg.src.line) and
(case_msg.src.column == std.math.maxInt(u32) or
actual_msg.column == case_msg.src.column) and
std.mem.eql(u8, expected_msg, actual_msg.msg) and
case_msg.src.kind == .note)
{
handled_errors[i] = true;
@ -817,7 +1069,7 @@ pub const TestContext = struct {
},
}
} else {
std.debug.print(
print(
"\nUnexpected note:\n{s}\n{}\n{s}",
.{ hr, ErrorMsg.init(note.*, .note), hr },
);
@ -827,7 +1079,7 @@ pub const TestContext = struct {
for (handled_errors) |handled, i| {
if (!handled) {
std.debug.print(
print(
"\nExpected error not found:\n{s}\n{}\n{s}",
.{ hr, case_error_list[i], hr },
);
@ -836,7 +1088,7 @@ pub const TestContext = struct {
}
if (any_failed) {
std.debug.print("\nupdate_index={d} ", .{update_index});
print("\nupdate_index={d} ", .{update_index});
return error.WrongCompileErrors;
}
},
@ -932,7 +1184,7 @@ pub const TestContext = struct {
.cwd_dir = tmp.dir,
.cwd = tmp_dir_path,
}) catch |err| {
std.debug.print("\nupdate_index={d} The following command failed with {s}:\n", .{
print("\nupdate_index={d} The following command failed with {s}:\n", .{
update_index, @errorName(err),
});
dumpArgs(argv.items);
@ -947,7 +1199,7 @@ pub const TestContext = struct {
switch (exec_result.term) {
.Exited => |code| {
if (code != 0) {
std.debug.print("\n{s}\n{s}: execution exited with code {d}:\n", .{
print("\n{s}\n{s}: execution exited with code {d}:\n", .{
exec_result.stderr, case.name, code,
});
dumpArgs(argv.items);
@ -955,7 +1207,7 @@ pub const TestContext = struct {
}
},
else => {
std.debug.print("\n{s}\n{s}: execution crashed:\n", .{
print("\n{s}\n{s}: execution crashed:\n", .{
exec_result.stderr, case.name,
});
dumpArgs(argv.items);
@ -974,7 +1226,9 @@ pub const TestContext = struct {
fn dumpArgs(argv: []const []const u8) void {
for (argv) |arg| {
std.debug.print("{s} ", .{arg});
print("{s} ", .{arg});
}
std.debug.print("\n", .{});
print("\n", .{});
}
const tmp_src_path = "tmp.zig";

View File

@ -754,7 +754,7 @@ pub fn render(gpa: *Allocator, nodes: []const Node) !std.zig.ast.Tree {
});
return std.zig.ast.Tree{
.source = ctx.buf.toOwnedSlice(),
.source = try ctx.buf.toOwnedSliceSentinel(0),
.tokens = ctx.tokens.toOwnedSlice(),
.nodes = ctx.nodes.toOwnedSlice(),
.extra_data = ctx.extra_data.toOwnedSlice(gpa),

View File

@ -1,5 +1,5 @@
const std = @import("std");
const TestContext = @import("../../src/test.zig").TestContext;
const TestContext = @import("../src/test.zig").TestContext;
// Self-hosted has differing levels of support for various architectures. For now we pass explicit
// target parameters to each test case. At some point we will take this to the next level and have
@ -12,19 +12,20 @@ const linux_x64 = std.zig.CrossTarget{
};
pub fn addCases(ctx: *TestContext) !void {
try @import("cbe.zig").addCases(ctx);
try @import("arm.zig").addCases(ctx);
try @import("aarch64.zig").addCases(ctx);
try @import("llvm.zig").addCases(ctx);
try @import("wasm.zig").addCases(ctx);
try @import("darwin.zig").addCases(ctx);
try @import("riscv64.zig").addCases(ctx);
try @import("compile_errors.zig").addCases(ctx);
try @import("stage2/cbe.zig").addCases(ctx);
try @import("stage2/arm.zig").addCases(ctx);
try @import("stage2/aarch64.zig").addCases(ctx);
try @import("stage2/llvm.zig").addCases(ctx);
try @import("stage2/wasm.zig").addCases(ctx);
try @import("stage2/darwin.zig").addCases(ctx);
try @import("stage2/riscv64.zig").addCases(ctx);
{
var case = ctx.exe("hello world with updates", linux_x64);
case.addError("", &[_][]const u8{
":93:9: error: struct 'test_case.test_case' has no member named 'main'",
":93:9: error: struct 'tmp.tmp' has no member named 'main'",
});
// Incorrect return type
@ -964,7 +965,7 @@ pub fn addCases(ctx: *TestContext) !void {
\\ defer return a();
\\}
, &[_][]const u8{
":7:8: error: try is not allowed inside defer expression",
":7:8: error: 'try' not allowed inside defer expression",
":10:8: error: cannot return from defer expression",
});
@ -1038,8 +1039,8 @@ pub fn addCases(ctx: *TestContext) !void {
\\ var i: u32 = 10;
\\}
, &[_][]const u8{
":3:9: error: redeclaration of 'i'",
":2:9: note: previously declared here",
":3:9: error: redeclaration of local variable 'i'",
":2:9: note: previous declaration here",
});
case.addError(
\\var testing: i64 = 10;
@ -1060,8 +1061,8 @@ pub fn addCases(ctx: *TestContext) !void {
\\ };
\\}
, &[_][]const u8{
":5:19: error: redeclaration of 'c'",
":4:19: note: previously declared here",
":5:19: error: redeclaration of local constant 'c'",
":4:19: note: previous declaration here",
});
}
@ -1213,7 +1214,7 @@ pub fn addCases(ctx: *TestContext) !void {
\\}
, &[_][]const u8{
":2:11: error: redefinition of label 'blk'",
":2:5: note: previous definition is here",
":2:5: note: previous definition here",
});
}

File diff suppressed because it is too large Load Diff

View File

@ -525,7 +525,7 @@ pub fn addCases(ctx: *TestContext) !void {
\\}
, &.{
":3:21: error: missing struct field: x",
":1:15: note: struct 'test_case.Point' declared here",
":1:15: note: struct 'tmp.Point' declared here",
});
case.addError(
\\const Point = struct { x: i32, y: i32 };
@ -538,7 +538,7 @@ pub fn addCases(ctx: *TestContext) !void {
\\ return p.y - p.x - p.x;
\\}
, &.{
":6:10: error: no field named 'z' in struct 'test_case.Point'",
":6:10: error: no field named 'z' in struct 'tmp.Point'",
":1:15: note: struct declared here",
});
case.addCompareOutput(
@ -591,6 +591,7 @@ pub fn addCases(ctx: *TestContext) !void {
, &.{
":3:5: error: enum fields cannot be marked comptime",
":8:8: error: enum fields do not have types",
":6:12: note: consider 'union(enum)' here to make it a tagged union",
});
// @enumToInt, @intToEnum, enum literal coercion, field access syntax, comparison, switch
@ -716,7 +717,7 @@ pub fn addCases(ctx: *TestContext) !void {
\\ _ = @intToEnum(E, 3);
\\}
, &.{
":3:9: error: enum 'test_case.E' has no tag with value 3",
":3:9: error: enum 'tmp.E' has no tag with value 3",
":1:11: note: enum declared here",
});
@ -732,7 +733,7 @@ pub fn addCases(ctx: *TestContext) !void {
, &.{
":4:5: error: switch must handle all possibilities",
":4:5: note: unhandled enumeration value: 'b'",
":1:11: note: enum 'test_case.E' declared here",
":1:11: note: enum 'tmp.E' declared here",
});
case.addError(
@ -787,7 +788,7 @@ pub fn addCases(ctx: *TestContext) !void {
\\ _ = E.d;
\\}
, &.{
":3:10: error: enum 'test_case.E' has no member named 'd'",
":3:10: error: enum 'tmp.E' has no member named 'd'",
":1:11: note: enum declared here",
});
@ -798,7 +799,7 @@ pub fn addCases(ctx: *TestContext) !void {
\\ _ = x;
\\}
, &.{
":3:17: error: enum 'test_case.E' has no field named 'd'",
":3:17: error: enum 'tmp.E' has no field named 'd'",
":1:11: note: enum declared here",
});
}

View File

@ -14,7 +14,7 @@ pub fn addCases(ctx: *TestContext) !void {
{
var case = ctx.exe("hello world with updates", target);
case.addError("", &[_][]const u8{
":93:9: error: struct 'test_case.test_case' has no member named 'main'",
":93:9: error: struct 'tmp.tmp' has no member named 'main'",
});
// Incorrect return type

View File

@ -16,7 +16,6 @@ const LibExeObjStep = build.LibExeObjStep;
const compare_output = @import("compare_output.zig");
const standalone = @import("standalone.zig");
const stack_traces = @import("stack_traces.zig");
const compile_errors = @import("compile_errors.zig");
const assemble_and_link = @import("assemble_and_link.zig");
const runtime_safety = @import("runtime_safety.zig");
const translate_c = @import("translate_c.zig");
@ -384,21 +383,6 @@ pub fn addRuntimeSafetyTests(b: *build.Builder, test_filter: ?[]const u8, modes:
return cases.step;
}
pub fn addCompileErrorTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode) *build.Step {
const cases = b.allocator.create(CompileErrorContext) catch unreachable;
cases.* = CompileErrorContext{
.b = b,
.step = b.step("test-compile-errors", "Run the compile error tests"),
.test_index = 0,
.test_filter = test_filter,
.modes = modes,
};
compile_errors.addCases(cases);
return cases.step;
}
pub fn addStandaloneTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode, skip_non_native: bool, target: std.zig.CrossTarget) *build.Step {
const cases = b.allocator.create(StandaloneContext) catch unreachable;
cases.* = StandaloneContext{
@ -840,304 +824,6 @@ pub const StackTracesContext = struct {
};
};
pub const CompileErrorContext = struct {
b: *build.Builder,
step: *build.Step,
test_index: usize,
test_filter: ?[]const u8,
modes: []const Mode,
const TestCase = struct {
name: []const u8,
sources: ArrayList(SourceFile),
expected_errors: ArrayList([]const u8),
expect_exact: bool,
link_libc: bool,
is_exe: bool,
is_test: bool,
target: CrossTarget = CrossTarget{},
const SourceFile = struct {
filename: []const u8,
source: []const u8,
};
pub fn addSourceFile(self: *TestCase, filename: []const u8, source: []const u8) void {
self.sources.append(SourceFile{
.filename = filename,
.source = source,
}) catch unreachable;
}
pub fn addExpectedError(self: *TestCase, text: []const u8) void {
self.expected_errors.append(text) catch unreachable;
}
};
const CompileCmpOutputStep = struct {
pub const base_id = .custom;
step: build.Step,
context: *CompileErrorContext,
name: []const u8,
test_index: usize,
case: *const TestCase,
build_mode: Mode,
write_src: *build.WriteFileStep,
const ErrLineIter = struct {
lines: mem.SplitIterator,
const source_file = "tmp.zig";
fn init(input: []const u8) ErrLineIter {
return ErrLineIter{ .lines = mem.split(input, "\n") };
}
fn next(self: *ErrLineIter) ?[]const u8 {
while (self.lines.next()) |line| {
if (mem.indexOf(u8, line, source_file) != null)
return line;
}
return null;
}
};
pub fn create(
context: *CompileErrorContext,
name: []const u8,
case: *const TestCase,
build_mode: Mode,
write_src: *build.WriteFileStep,
) *CompileCmpOutputStep {
const allocator = context.b.allocator;
const ptr = allocator.create(CompileCmpOutputStep) catch unreachable;
ptr.* = CompileCmpOutputStep{
.step = build.Step.init(.custom, "CompileCmpOutput", allocator, make),
.context = context,
.name = name,
.test_index = context.test_index,
.case = case,
.build_mode = build_mode,
.write_src = write_src,
};
context.test_index += 1;
return ptr;
}
fn make(step: *build.Step) !void {
const self = @fieldParentPtr(CompileCmpOutputStep, "step", step);
const b = self.context.b;
var zig_args = ArrayList([]const u8).init(b.allocator);
zig_args.append(b.zig_exe) catch unreachable;
if (self.case.is_exe) {
try zig_args.append("build-exe");
} else if (self.case.is_test) {
try zig_args.append("test");
} else {
try zig_args.append("build-obj");
}
const root_src_basename = self.case.sources.items[0].filename;
try zig_args.append(self.write_src.getFileSource(root_src_basename).?.getPath(b));
zig_args.append("--name") catch unreachable;
zig_args.append("test") catch unreachable;
if (!self.case.target.isNative()) {
try zig_args.append("-target");
try zig_args.append(try self.case.target.zigTriple(b.allocator));
}
zig_args.append("-O") catch unreachable;
zig_args.append(@tagName(self.build_mode)) catch unreachable;
warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name });
if (b.verbose) {
printInvocation(zig_args.items);
}
const child = std.ChildProcess.init(zig_args.items, b.allocator) catch unreachable;
defer child.deinit();
child.env_map = b.env_map;
child.stdin_behavior = .Ignore;
child.stdout_behavior = .Pipe;
child.stderr_behavior = .Pipe;
child.spawn() catch |err| debug.panic("Unable to spawn {s}: {s}\n", .{ zig_args.items[0], @errorName(err) });
var stdout_buf = ArrayList(u8).init(b.allocator);
var stderr_buf = ArrayList(u8).init(b.allocator);
child.stdout.?.reader().readAllArrayList(&stdout_buf, max_stdout_size) catch unreachable;
child.stderr.?.reader().readAllArrayList(&stderr_buf, max_stdout_size) catch unreachable;
const term = child.wait() catch |err| {
debug.panic("Unable to spawn {s}: {s}\n", .{ zig_args.items[0], @errorName(err) });
};
switch (term) {
.Exited => |code| {
if (code == 0) {
printInvocation(zig_args.items);
return error.CompilationIncorrectlySucceeded;
}
},
else => {
warn("Process {s} terminated unexpectedly\n", .{b.zig_exe});
printInvocation(zig_args.items);
return error.TestFailed;
},
}
const stdout = stdout_buf.items;
const stderr = stderr_buf.items;
if (stdout.len != 0) {
warn(
\\
\\Expected empty stdout, instead found:
\\================================================
\\{s}
\\================================================
\\
, .{stdout});
return error.TestFailed;
}
var ok = true;
if (self.case.expect_exact) {
var err_iter = ErrLineIter.init(stderr);
var i: usize = 0;
ok = while (err_iter.next()) |line| : (i += 1) {
if (i >= self.case.expected_errors.items.len) break false;
const expected = self.case.expected_errors.items[i];
if (mem.indexOf(u8, line, expected) == null) break false;
continue;
} else true;
ok = ok and i == self.case.expected_errors.items.len;
if (!ok) {
warn("\n======== Expected these compile errors: ========\n", .{});
for (self.case.expected_errors.items) |expected| {
warn("{s}\n", .{expected});
}
}
} else {
for (self.case.expected_errors.items) |expected| {
if (mem.indexOf(u8, stderr, expected) == null) {
warn(
\\
\\=========== Expected compile error: ============
\\{s}
\\
, .{expected});
ok = false;
break;
}
}
}
if (!ok) {
warn(
\\================= Full output: =================
\\{s}
\\
, .{stderr});
return error.TestFailed;
}
warn("OK\n", .{});
}
};
pub fn create(
self: *CompileErrorContext,
name: []const u8,
source: []const u8,
expected_lines: []const []const u8,
) *TestCase {
const tc = self.b.allocator.create(TestCase) catch unreachable;
tc.* = TestCase{
.name = name,
.sources = ArrayList(TestCase.SourceFile).init(self.b.allocator),
.expected_errors = ArrayList([]const u8).init(self.b.allocator),
.expect_exact = false,
.link_libc = false,
.is_exe = false,
.is_test = false,
};
tc.addSourceFile("tmp.zig", source);
var arg_i: usize = 0;
while (arg_i < expected_lines.len) : (arg_i += 1) {
tc.addExpectedError(expected_lines[arg_i]);
}
return tc;
}
pub fn addC(self: *CompileErrorContext, name: []const u8, source: []const u8, expected_lines: []const []const u8) void {
var tc = self.create(name, source, expected_lines);
tc.link_libc = true;
self.addCase(tc);
}
pub fn addExe(
self: *CompileErrorContext,
name: []const u8,
source: []const u8,
expected_lines: []const []const u8,
) void {
var tc = self.create(name, source, expected_lines);
tc.is_exe = true;
self.addCase(tc);
}
pub fn add(
self: *CompileErrorContext,
name: []const u8,
source: []const u8,
expected_lines: []const []const u8,
) void {
const tc = self.create(name, source, expected_lines);
self.addCase(tc);
}
pub fn addTest(
self: *CompileErrorContext,
name: []const u8,
source: []const u8,
expected_lines: []const []const u8,
) void {
const tc = self.create(name, source, expected_lines);
tc.is_test = true;
self.addCase(tc);
}
pub fn addCase(self: *CompileErrorContext, case: *const TestCase) void {
const b = self.b;
const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {s}", .{
case.name,
}) catch unreachable;
if (self.test_filter) |filter| {
if (mem.indexOf(u8, annotated_case_name, filter) == null) return;
}
const write_src = b.addWriteFiles();
for (case.sources.items) |src_file| {
write_src.add(src_file.filename, src_file.source);
}
const compile_and_cmp_errors = CompileCmpOutputStep.create(self, annotated_case_name, case, .Debug, write_src);
compile_and_cmp_errors.step.dependOn(&write_src.step);
self.step.dependOn(&compile_and_cmp_errors.step);
}
};
pub const StandaloneContext = struct {
b: *build.Builder,
step: *build.Step,
@ -1312,13 +998,6 @@ pub const GenHContext = struct {
}
};
fn printInvocation(args: []const []const u8) void {
for (args) |arg| {
warn("{s} ", .{arg});
}
warn("\n", .{});
}
pub fn create(
self: *GenHContext,
filename: []const u8,