v icon indicating copy to clipboard operation
v copied to clipboard

.str() inside of [...] parsed incorrectly

Open Undumendil opened this issue 7 years ago • 9 comments

Input:

fn main() {
    mut m := map[string]int{}
    m['1'] = 1 
    println(m[1.str()])
}

Expected output: 1 Output:

expected `]` but got `str`

Undumendil avatar Jun 18 '19 23:06 Undumendil

but this works

fn main() {
	mut m := map[string]int{}
	m['1'] = 1
	n := 1
	println(m[n.str()])
}

fauzipadlaw avatar Jun 19 '19 10:06 fauzipadlaw

This does not:

fn main() {
    mut m := map[string]int{}
    m['1'] = 1 
    n := 0 
    println(m[(n + 1).str()])
}

You just found a bug. V can't compile this program, but it should. Please create a GitHub issue.

Undumendil avatar Jun 19 '19 10:06 Undumendil

yas, this doesn't either

fn main() {
    mut m := map[string]int{}
    m['1'] = 1 
    n := 0 
    o := 1
    println(m[(n + o).str()])
}

fauzipadlaw avatar Jun 19 '19 10:06 fauzipadlaw

The reason why 1.str() does not work is because at this point 1 is a literal. literals do not know any function, they only know their value.

Once you make it into a variable however like this n := 1 . n becomes an instance of a type int, not of a literal 1. And you can call functions on types like .str().

You can call methods on types, not on literals.

fabulousduck avatar Jun 25 '19 13:06 fabulousduck

It's a bit weird if literal 1 doesn't have a defined type, because it can initialize a variable i := 1. The programmer has to think of 1 as an int.

(n + o).str() should be allowed as the receiver is not mutable. n + o does have a type, it just doesn't have an address.

ntrel avatar Jun 25 '19 17:06 ntrel

Interesting problem.

Literals are going to be like in Go, typeless. So that you can do a := 1 + 2.1 (a is f64, so is 1)

But I think 1.str() should be allowed.

medvednikov avatar Jun 26 '19 19:06 medvednikov

If you do this for int, it would make sense to have it for float, no?

Something like .str(precision, rounding) so that 1.23456.str(3, true) would return “1.235” with both precision and rounding being optional.

If not, then perhaps a function str(value, precision, rounding): Println(str(1) + “ is not equal to “ + str(1.2345, 3, true)) returning “1 is not equal to 1.235”

lazalong avatar Jul 02 '19 12:07 lazalong

This has become weird now. This doesn't work:

fn main() {
    mut m := map[string]int
    m['1'] = 1 
    println(m[1.str()])
}

It returns this error:

test.v:4:19: expected type `string`, but got `f32`

But this does work:

fn main() {
    mut m := map[string]int
    m['1'] = 1 
    println(m[(1).str()])
}

Bowero avatar Aug 27 '19 08:08 Bowero

Fixed, your example works now.

medvednikov avatar Apr 03 '20 20:04 medvednikov