Skip to content

Silent wrong value: Type.from_int(n) truncates n to the repr, so an out-of-range integer returns Some (Tiny.from_int(456) is Some(Hi = 200)) #1499

Closed

Description

@ehartford

Summary

Type.from_int(n) truncates n to the repr before comparing it with the discriminants, so an integer outside the repr's range that shares low bits with a discriminant returns Some of that variant. Silent wrong value.

Repro (installed nightly v0.15.2.1; the #1453 branch stage1)

enum Tiny: u8:
    Lo = 3
    Hi = 200

enum K: i32:
    A = 1

fn main:
    let n: i32 = 456
    match Tiny.from_int(n):
        Some(t) => print(t as u8)
        None => print("none")
    let m: i64 = 4294967297
    match K.from_int(m):
        Some(.A) => print("a")
        None => print("none")
    let neg: i32 = -56
    match Tiny.from_int(neg):
        Some(t) => print(t as u8)
        None => print("none")

Prints 200, a, 200; expected none three times (456, 2^32+1 and -56 are no discriminant of their enum).

Spec

§4.4a: "Type.from_int(n) converts an integer to Option[Type], returning .None for values that don't match any defined discriminant".

Root cause (reading)

src/Codegen.w gen_disc_enum_from_int_val: let input = self.coerce_int(arg_val, repr_ty) narrows the argument to the repr before the switch; the comparison must be at a width holding both the argument and the repr (with each side extended by its own signedness), or reject an argument outside the repr's range first.

Found while fixing #1453 (from_int's type).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions