Skip to content

Bug: cannot implicitly cast error union payloads #2561

@fengb

Description

@fengb

Basic test cases:

const std = @import("std");
const testing = std.testing;

test "int assignment" {
    var a: anyerror!i32 = @as(i16, 1); // error: expected type 'anyerror!i32', found 'i16'
    _ = a catch {};
}

test "error union assignment" {
    var a: anyerror!i16 = 1;
    var b: anyerror!i32 = a; // error: expected type 'anyerror!i32', found 'anyerror!i16'
    // note: error union payload 'i16' cannot cast into error union payload 'i32'
    _ = b;
}

fn makeErrorUnion(comptime T: type) !T {
    return error.OutOfMemory;
}

fn doesNotWork() !u32 {
    return makeErrorUnion(u16); // error: expected type '@typeOf(doesNotWork).ReturnType.ErrorSet!u32', found '@typeOf(makeError).ReturnType.ErrorSet!u16'
    // note: error union payload 'u16' cannot cast into error union payload 'u32'
}

test "func call" {
    _ = doesNotWork() catch null;
}

fn allocExtended(allocator: std.mem.Allocator, memsize: usize) !u8 {
    return allocator.alignedAlloc(u8, 4096, memsize); // error: expected type '@typeOf(allocExtended).ReturnType.ErrorSet!u8', found '@typeOf(std.mem.Allocator.alignedAlloc).ReturnType.ErrorSet![]align(4096) u8'
    // note: error union payload '[]align(4096) u8' cannot cast into error union payload 'u8'

    // adding try fixes this
    // return try allocator.alignedAlloc(u8, 4096, memsize);
}

test "func call alignment" {
    var buf: [100]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&buf);
    const allocator = fba.allocator();

    _ = allocExtended(allocator, 123) catch []u8{};
}

I had a hard time reproducing the alignment case with simple assignments.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviorfrontendTokenization, parsing, AstGen, Sema, and Liveness.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions