Skip to content

Wrong representation generated for enum #152

@arnetheduck

Description

@arnetheduck

Consider:

typedef enum my_enum : char {
   VALUE
} my_enum;

Per cppreference:

An enumerated type is a distinct type whose value is a value of its underlying type (see below), which includes the values of explicitly named constants (enumeration constants).

In particular, the valid values of an enum are not limited to the "named constants". Instead, the valid values are all those that are valid for the underlying type.

Using a minimal wrapper:

import "../src/futhark"

importc:
  path "."
  "tenum.h"

echo my_enum.VALUE

Futhark wraps the above as:

type
  enum_my_enum_570425771* {.size: sizeof(cschar).} = enum
    VALUE = 0

Semantically, this mapping is incorrect in that it does not correspond to how enums are defined (and often used) in C - instead, it's based on an opinionated interpretation which ends up being a footgun for inexperienced nim users who are not familiar with the semantics of C.

The closes Nim equivalent mapping for any enum in c is a distinct <underlying_type> with values being const of that type and with the integer/boolean operators (or etc) borrowed (so that enum values can be combined.

If the opinionated version is desired, it should be optional / explicitly chosen and come with a "parse" function that gives returns an error for values that are valid for the underlying type but not part of the named constants - this "parse" function is critical for correct usage of C enums from Nim, so that users are aware that values coming from C must always be sanitized to the more strictly defined Nim enum.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions