From 2e562a5f366aabefd34a4191b2cd0b5e72d3d089 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 25 Sep 2018 12:03:39 -0400 Subject: [PATCH] fix crash on runtime index into slice of comptime type closes #1435 --- src/analyze.cpp | 7 +++++-- src/ir.cpp | 6 ++++++ test/compile_errors.zig | 16 ++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/analyze.cpp b/src/analyze.cpp index ca80958887..650f5b6b11 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -1187,8 +1187,11 @@ ZigType *get_fn_type(CodeGen *g, FnTypeId *fn_type_id) { if ((err = type_resolve(g, type_entry, ResolveStatusZeroBitsKnown))) return g->builtin_types.entry_invalid; - if (is_c_abi) + if (is_c_abi) { + if ((err = type_resolve(g, type_entry, ResolveStatusSizeKnown))) + return g->builtin_types.entry_invalid; continue; + } if (type_has_bits(type_entry)) { ZigType *gen_type; @@ -4464,7 +4467,7 @@ bool handle_is_ptr(ZigType *type_entry) { return type_has_bits(type_entry->data.maybe.child_type) && !type_is_codegen_pointer(type_entry->data.maybe.child_type); case ZigTypeIdUnion: - assert(type_entry->data.unionation.complete); + assert(type_entry->data.unionation.zero_bits_known); if (type_entry->data.unionation.gen_field_count == 0) return false; if (!type_has_bits(type_entry)) diff --git a/src/ir.cpp b/src/ir.cpp index 95172e2b59..33d42cfc5f 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -14640,6 +14640,12 @@ static ZigType *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstructionEle } else { // runtime known element index + if (type_requires_comptime(return_type)) { + ir_add_error(ira, elem_index, + buf_sprintf("values of type '%s' must be comptime known, but index value is runtime known", + buf_ptr(&return_type->data.pointer.child_type->name))); + return ira->codegen->builtin_types.entry_invalid; + } if (ptr_align < abi_align) { if (elem_size >= ptr_align && elem_size % ptr_align == 0) { return_type = adjust_ptr_align(ira->codegen, return_type, ptr_align); diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 5d9fb84c71..d5d0cb38f2 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -1,6 +1,22 @@ const tests = @import("tests.zig"); pub fn addCases(cases: *tests.CompileErrorContext) void { + cases.add( + "runtime index into comptime type slice", + \\const Struct = struct { + \\ a: u32, + \\}; + \\fn getIndex() usize { + \\ return 2; + \\} + \\export fn entry() void { + \\ const index = getIndex(); + \\ const field = @typeInfo(Struct).Struct.fields[index]; + \\} + , + ".tmp_source.zig:9:51: error: values of type 'StructField' must be comptime known, but index value is runtime known", + ); + cases.add( "compile log statement inside function which must be comptime evaluated", \\fn Foo(comptime T: type) type {