c3lang / c3c

Compiler for the C3 language
https://c3-lang.org
GNU Lesser General Public License v3.0
2.96k stars 182 forks source link

Unclear compiler error on cases in macro arguments #1606

Closed loafoflead closed 3 days ago

loafoflead commented 4 days ago

When writing macros that take types as arguments, if the type is named with a lowercase identifier (e.g. 'type', instead of 'Type'), the compiler emits a very cryptic message.

The following functions fine:

macro get_type($Type, idx) {
        $switch ($Type)
        // (...)
        $endswitch
}

And when called return the expected result.

However when 'Type' is 'type', the compiler emits the following error when trying to call the macro:

18: String s = get_type(String, 0);
                        ^^^^^
(test.c3:18:22) Error: A type must be followed by either (...) or '.'.

6: macro get_type($type, idx) {
         ^^^^^^^
FATAL ERROR Should be unreachable -> in expr_is_constant_eval @ in /home/runner/work/c3c/c3c/src/compiler/expr.c:346

Sorry if this is just a skill issue, but I couldn't find any mention of the importance of case-sensitivity in the docs on macros, and only found this out through trial and error and in the source code.

Perhaps just a mention in the 'Macros' section that types need to have the correct case as in the rest of the language (which makes sense) would be good, or a compiler message that says 'Incorrect case'.

Below is the full code snippet:

import std::io;

const String[] STRING_LIST = {"hello", "world"};
const int[] INT_LIST = {1, 2, 3};

// change 'Type' to 'type'
macro get_type($Type, idx) {
        $switch ($Type)
        $case String:
                return STRING_LIST[idx];
        $case int:
                return INT_LIST[idx];
        $default:
                return 0;
        $endswitch
}

fn int main() {
        String s = get_type(String, 0);
        int i = get_type(int, 0);
        return 0;
}
lerno commented 3 days ago

That error is indeed uninformative, I've updated it. However this is more worrying:

FATAL ERROR Should be unreachable -> in expr_is_constant_eval @ in /home/runner/work/c3c/c3c/src/compiler/expr.c:346

In what version do you see this? I hope it's not reproducible in 0.6.4

loafoflead commented 3 days ago

The error is not reproducible in 0.6.4, the fatal error was in 0.5 I think.

Will make sure to include version of compiler in future issues 👍.

lerno commented 3 days ago

Thank you for reporting unclear errors, those are indeed important.