oridb / mc

Myrddin Compiler
MIT License
387 stars 34 forks source link

Incorrect shadowing when variable has same name as package #158

Closed snocl closed 6 years ago

snocl commented 6 years ago

If a variable is named the same as an imported package, its fields can’t be accessed normally. It can, however, be accessed indirectly through dereferencing. For example:

use std

type strukt = struct
    field : int
;;

const main = {
    var std : strukt = [.field = 1]
    std.field = 2     // This fails with 'undeclared var std.field'.
    (&std)#.field = 3 // Silly workaround.
}

(If the field is a pointer then std#.field will work while std.field will still fail.)

I’d expect the correct behavior to either be a compile-time error when declaring the variable, or for the compiler to always have the local variable shadow the package.

oridb commented 6 years ago

Hm. On one hand it's definitely weird, on the other hand, at the very least it makes sense to shadow the package name from within the package, so you can do:

 var re : regex.regex

I think I'll make it work.

oridb commented 6 years ago

Turned out to be really easy.

snocl commented 6 years ago

My concrete case was similar: var board : board.board. :)

Realized pretty quickly that shadowing it would mean I couldn’t access the related functions, though...

oridb commented 6 years ago

Yeah. It makes sense to do it from within a namespace, so you might have regex.regex(args). That used to be subject to the same aliasing weirdness, but I don't think I've ever exported a global struct, so I never ran into it.

From outside of a namespace, it's definitely less useful, but that's no excuse for stupid behavior.