poke-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [RFC] A new mechanism to access the active field of unions


From: Jose E. Marchesi
Subject: Re: [RFC] A new mechanism to access the active field of unions
Date: Thu, 04 Mar 2021 20:51:15 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/28.0.50 (gnu/linux)

Hi Mohammad.


> The current approach to deal with unions using exception is not elegant.
>
> ```poke
> try u.field1 = 1;
> catch if E_elem {};
> ```
>
> These are my initial ideas regarding this problem:
>
>
> === Option 1. Overloading of `isa` operator
>
> ```poke
> if (u isa TargetType) {
> }
> ```
>
> But overloading `isa` operator will change the current behavior:
>
> ```poke
> type U1 =
>   union
>   {
>     int i;
>   };
> var u1 = U1 {};
>
> // current behavior
> assert (u1 isa U);
> assert (!(u1 isa int));
> ```

The overloading of the `isa' operator would get a value at the left side
and an identifier at the right side, not a type.  Like in:

  type U1 =
     union
     {
       int i : i > 0;
       long l;
     };

  var u1 = U1 {};

  (poke) u1 isa i
  1
  (poke) u1 isa l
  0
  (poke) u1 isa quux
  error: invalid member `quux'

> === Option 2. A new operator (e.g., `holds`)
>
> ```poke
> assert (u1 isa U);
> assert (u1 holds int);
> ```
>
> But there's an issue here, `union`s, almost always are not defined as a type.

This would be resolved if the right operator of `holds' is a field
name/identifier.  But then it is just like Option 1 with a different
name for the operator.

> === Option 3. Adding more reflection (introspection) facilities to unions
>
> ```poke
> if (frm.u'holds("text")) {
>   /* ... */
> } else if (frm.u'holds("frame_data")) {
>   /* ... */
> }
>
> assert (frm.u'fields in ["text", "frame_data"]);
> ```

This could also be achieved by having isa/hold to get a string at the
right side instead of an identifier:


  frm.u isa "text"

So, to summarize:


  VAL isa TYPE

    Checks whether VAL is of type TYPE.
    This already works.

  VAL isa IDENTIFIER

    Checks whether VAL is an union value _and_ has a field named
    IDENTIFIER.

  VAL isa STR

    Checks whether VAL is an union value _and_ has a field named STR.

If reusing `isa' like that is confusing, we can come with a new syntax
for the second and third usages, like:

    VAL?.IDENTIFIER
    VAL?."STR"

or something like that...



reply via email to

[Prev in Thread] Current Thread [Next in Thread]