nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.41k stars 1.47k forks source link

fields and fieldPairs "yield" mutable fields #9004

Open mratsim opened 5 years ago

mratsim commented 5 years ago

The fields "yielded" by fields and fieldPairs are mutable if the object is mutable.

This is not a problem per se but it's undocumented, is that something we can rely on or an implementation leak?

Note: the description mentions The current implementation also has a bug that affects symbol binding in the loop body. without going into more details.

Test case:

type
  Foo = object
    data: int

  Bar = object
    data: string

func baz(typ: typedesc[object]): typ =
  for name, value in result.fieldPairs:
    when value is int:
      value = 123
    elif value is string:
      value = "123"

let foo = baz(Foo)
echo foo # (data: 123)

let bar = baz(Bar)
echo bar # (data: "123")
Araq commented 5 years ago

This is not a problem per se but it's undocumented, is that something we can rely on or an implementation leak?

You can rely on it. (Though we need to ensure it keeps working with a test and document it.)

dom96 commented 5 years ago

Interesting bug I noticed: if you pass value to a procedure like for example proc foo(x: var int64) (under the is int branch) then you'll get this error:

Error: for a 'var' type a variable needs to be passed; but 'int64(o.field1)' is immutable

Guessing this is because the compiler does a rewrite (note that the above is from my code which uses different field/obj names).