Commit 4d8269f69f

Andrew Kelley <superjoe30@gmail.com>
2017-08-26 01:53:29
fix some casts on const data causing segfault
1 parent 754f780
Changed files (2)
src
test
cases
src/ir.cpp
@@ -7330,7 +7330,7 @@ static void eval_const_expr_implicit_cast(CastOp cast_op,
         case CastOpResizeSlice:
         case CastOpBytesToSlice:
             // can't do it
-            break;
+            zig_unreachable();
         case CastOpIntToFloat:
             {
                 assert(new_type->id == TypeTableEntryIdFloat);
@@ -7366,7 +7366,9 @@ static void eval_const_expr_implicit_cast(CastOp cast_op,
 static IrInstruction *ir_resolve_cast(IrAnalyze *ira, IrInstruction *source_instr, IrInstruction *value,
         TypeTableEntry *wanted_type, CastOp cast_op, bool need_alloca)
 {
-    if (value->value.special != ConstValSpecialRuntime) {
+    if (value->value.special != ConstValSpecialRuntime &&
+        cast_op != CastOpResizeSlice && cast_op != CastOpBytesToSlice)
+    {
         IrInstruction *result = ir_create_const(&ira->new_irb, source_instr->scope,
                 source_instr->source_node, wanted_type);
         eval_const_expr_implicit_cast(cast_op, &value->value, value->value.type,
@@ -8166,7 +8168,7 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
         }
     }
 
-    // expliict cast from &const [N]T to []const T
+    // explicit cast from &const [N]T to []const T
     if (is_slice(wanted_type) &&
         actual_type->id == TypeTableEntryIdPointer &&
         actual_type->data.pointer.is_const &&
test/cases/cast.zig
@@ -275,3 +275,12 @@ fn cast128Int(x: f128) -> u128 {
 fn cast128Float(x: u128) -> f128 {
     @bitCast(f128, x)
 }
+
+test "const slice widen cast" {
+    const bytes = []u8{0x12, 0x12, 0x12, 0x12};
+
+    const u32_value = ([]const u32)(bytes[0..])[0];
+    assert(u32_value == 0x12121212);
+
+    //assert(@bitCast(u32, bytes) == 0x12121212);
+}