Skip to content

bug: 'in' operator does not validate type compatibility between value and collection elements #1589

@SchoolyB

Description

@SchoolyB

Description

The in and not_in operators do not validate that the left-hand value's type matches the element type of the right-hand collection. Mismatched types pass the typechecker and crash during C compilation.

Reproduction

do main() {
    mut arr [int] = {1, 2, 3}
    if "hello" in arr {
        println("found")
    }
}

Expected: Compile error — cannot check if a string is in an [int] array

Actual: Typechecker passes, C compilation fails:

error: passing 'EzString' to parameter of incompatible type 'int64_t'
    if (ez_arrays_contains_int(&arr, ez_string_lit("hello"))) {

Additional Cases

These should also be caught:

// string in [bool]
mut flags [bool] = {true, false}
if "yes" in flags { }

// int in [string]
mut names [string] = {"alice", "bob"}
if 42 in names { }

// bool in [int]  
mut nums [int] = {1, 2, 3}
if true in nums { }

// Also applies to not_in / !in
if "hello" not_in arr { }

Maps should also be checked — the in operator checks map keys, so the value type must match the key type:

mut m map[string:int] = {"a": 1}
if 42 in m { }  // int cannot be a key in map[string:int]

Root Cause

The typechecker resolves the in / not_in expression but does not compare the left operand's type against the collection's element type (for arrays) or key type (for maps). The codegen then emits a type-specific ez_arrays_contains_<type>() call based on the array's element type, passing the mismatched left operand directly — which causes a C type error.

Fix

In the typechecker's in / not_in handler, after resolving both operand types:

  1. If the right side is an array, verify the left operand's type matches the array's element type
  2. If the right side is a map, verify the left operand's type matches the map's key type
  3. If mismatched, emit an error like: cannot check if 'string' is in '[int]'; element type is 'int'

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtypecheckerRelated to type checking and validation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions