edubart / nelua-lang

Minimal, efficient, statically-typed and meta-programmable systems programming language heavily inspired by Lua, which compiles to C and native code.
https://nelua.io
MIT License
2k stars 62 forks source link

Weird behavior when messing with type inference #129

Closed stefanos82 closed 2 years ago

stefanos82 commented 2 years ago

I have hard time understanding how type inference works and decided to play more to finally grasp its semantics.

While I was doing so, the following code caused a problem:

require 'io'
require 'string'

do
  local msgv1 : auto = "hello"
  io.printf("%s from Nelua world!\n", msgv1)
  local msgv2 : string = "greetings"
  io.printf("%s from Nelua world!\n", msgv2)
  local msgv3 : type = #[msgv1.type]#
  io.printf("%s from New Nelua world!\n", msgv3)
end

image

The problem takes place when I attempt to use #[msgv1.type]# to get my first variable's type.

Now, I know that local msgv3 : type = #[msgv1.type]# is wrong and it should be msgv3 : #[msgv1.type]# = "Saludos" in order to work.

Why has it tried to build in the first place without complaining about its logic is the real question...

P.S.: would not it be nice to have a shortcut for types? For instance, in my case it could be @"" to get the strings type.

edubart commented 2 years ago

You have discovered an unimplemented feature, that triggered a compile bug, thanks for reporting. I've fixed this in commit https://github.com/edubart/nelua-lang/commit/703bc2cbf708eb4c25114b554dbe4376d153d48f.

stefanos82 commented 2 years ago

After reporting this issue, I've got curious to study the generated C code; of course the Nelua code has been tweaked (updated) a bit and now looks like this:

require 'io'

do
  local msgv1 : auto = "hello"
  io.printf("%s from Nelua world!\n", msgv1)
  io.printf(
    "'%s' is of type '%s'\n",
    #[tostring(msgv1.name)]#, #[tostring(msgv1.type)]#
  )
  local msgv2 : string = "greetings"
  io.printf("%s from Nelua world!\n", msgv2)
  local msgv3 : #[msgv1.type]# = "Saludos"
  io.printf("%s from New Nelua world!\n", msgv3)
end

What caught my attention in generated C code is the following line:

image

Under which circumstances if() will not get executed?

edubart commented 2 years ago

Under which circumstances if() will not get executed?

It will always be executed, the Nelua compiler does not simplify code of branches that are always true or false, but this is not a problem because the C compiler will simplify this at his optimizing stage. Nevertheless I've changed the code to not generate that if(true) anymore.

stefanos82 commented 2 years ago

Ah I see, very well :+1: