v icon indicating copy to clipboard operation
v copied to clipboard

Error accessing optional from struct via method

Open kylepritchard opened this issue 2 years ago • 0 comments

Describe the bug

When trying to access a optional field in a struct through a struct method there is a compiler fault. It works OK if the field is accessed from main function.

Expected Behavior

If the code is correct in the example given then a panic should be raised because the value of field is 'none'

Current Behavior

C:\Users\kylep\Desktop\lorca\testing>v run optional_str.v
==================
C:/Users/kylep/AppData/Local/Temp/v_0/optional_str.16159520470198910903.tmp.c:7581: warning: cast between pointer and integer of different size
C:/Users/kylep/AppData/Local/Temp/v_0/optional_str.16159520470198910903.tmp.c:12447: error: expected struct or union but not 'struct main__JsonParser *'
...
==================
(Use `v -cg` to print the entire error message)

builder error:
==================
C error. This should never happen.

This is a compiler bug, please report it using `v bug file.v`.

https://github.com/vlang/v/issues/new/choose

You can also use #help on Discord: https://discord.gg/vlang

Reproduction Steps

module main

struct JsonParser {
mut:
	js        string
	tokens    []string
	pos       int
	tok_next  int
	tok_super ?int
}

fn new_parser(qty int) JsonParser {
	return JsonParser{
		tokens: []string{cap: qty}
	}
}

fn (mut p JsonParser) parse() int {
	j := p.tok_super or { panic('nan') }
	return j
}

fn main() {
	mut x := new_parser(100)
	i := x.parse()
	println(i)
}

Possible Solution

No response

Additional Information/Context

looking at the generated code (I'm not good in C), it appears that it is not accessing the field correctly.

_option_int _t1 = p.tok_super;

I believe it should be

_option_int _t1 = p->tok_super;

but could be wrong!

V version

V 0.3.3 cdc0159

Environment details (OS name and version, etc.)

OS: windows, Microsoft Windows 11 Pro v22621 64-bit Processor: 8 cpus, 64bit, little endian, CC version: Error: exec failed (CreateProcess) with code 2: The system cannot find the file specified. cmd: cc --version

getwd: C:\Users\kylep\Desktop\lorca\testing vmodules: C:\Users\kylep.vmodules vroot: C:\v vexe: C:\v\v.exe vexe mtime: 2023-03-01 13:54:31 is vroot writable: true is vmodules writable: true V full version: V 0.3.3 19ba7c5.cdc0159

Git version: git version 2.35.0.windows.1 Git vroot status: weekly.2023.09-13-gcdc0159c-dirty .git/config present: true thirdparty/tcc status: thirdparty-windows-amd64 1e6e7c6f

kylepritchard avatar Mar 01 '23 14:03 kylepritchard