A better unreachable

Suppose I have

    pub fn fail(self: *Self, kind: ErrorType, loc: Token.Loc) Error!void {
        self.error_type = kind;
        self.error_loc = loc;
        return error.ParsingFailed;
    }

and then use it like below. I understand that I can add a type argument to match avoid using unreachable, e.g.

pub fn fail(self: *Self, T: type, kind: ErrorType, loc: Token.Loc) Error!T {...}

but is there a way to avoid both the type argument and unreachable?

    pub fn getSymbol(self: *Self, id: AST.Ident, symbol_types: anytype) Error!AST.Symbol {
        const T = AST.Symbol;
        const temp = self.symbols.get(id.name);
        if (temp == null) {
            self.fail(T, .unknown_symbol, id.loc);
            unreachable;
        }
        if (symbol_types.len == 0)
            return;
        const symbol = temp.?;
        for (symbol_types) |kind| {
            if (symbol.kind == kind)
                return symbol;
        }
        try self.fail(T, .invalid_symbol, id.loc);
        unreachable;
    }

Not sure I understood correctly the problem but if your fail function always returns an error, you can leave the first definition and just call return self.fail(.unknown_symbol, id.loc)

You can change the function’s definition to return only Error instead of Error!void.

You’ll exit scope returning Error and unreachable is no longer needed

2 Likes

Bingo! I didn’t know a function could return just Error!

Took me some times to figure it out but I was facing the same use case :wink:

1 Like