v icon indicating copy to clipboard operation
v copied to clipboard

checker: add warn about non-option function

Open felipensp opened this issue 2 years ago • 3 comments

This PR is about the ROADMAP item "Handle function pointers safely, remove if function == 0 {".


type MapFunc = fn () 

struct Test {
	a fn (int) // warn
	b ?fn () // ok
	c MapFunc // warn
	d ?MapFunc // ok
}

fn main() {
	t := Test{b: fn () {
		println('cool')
	}}
	z := t.b?
	z()
	dump(t)
}
$ v run bug.v
bug.v:2:16: warning: you should declare it as Option instead
    1 | 
    2 | type MapFunc = fn () 
      |                ~~~~~~
    3 | 
    4 | struct Test {
bug.v:5:4: warning: you should declare it as Option instead (?fn ...)
    3 | 
    4 | struct Test {
    5 |     a fn (int) // warn
      |       ~~~~~~~~
    6 |     b ?fn () // ok
    7 |     c MapFunc // warn
bug.v:7:4: warning: this is not recommended, you should use Option function instead
    5 |     a fn (int) // warn
    6 |     b ?fn () // ok
    7 |     c MapFunc // warn
      |       ~~~~~~~
    8 |     d ?MapFunc // ok
    9 | }
cool
[bug.v:17] t: Test{
    a: fn (int)
    b: Option(fn ())
    c: fn ()
    d: Option(none)
}

🤖 Generated by Copilot at 100f441

Warn about direct function types in struct fields. The change modifies vlib/v/checker/struct.v to emit a warning when a struct field is declared as a direct function type without the option flag, as this can cause memory issues. The change is part of a pull request to improve function type safety in V.

🤖 Generated by Copilot at 100f441

  • Add a warning message for direct function types in struct fields (link)

felipensp avatar Jun 25 '23 18:06 felipensp

@medvednikov Should we make possible to do "t.b?()" too?

felipensp avatar Jun 25 '23 18:06 felipensp

imho, this should be a notice instead of a warning, at least for now

spytheman avatar Jun 27 '23 09:06 spytheman

This PR also closes #9977 probably. Or not?

ArtemkaKun avatar Jul 03 '23 20:07 ArtemkaKun

Already implemented as notices.

felipensp avatar Dec 10 '24 11:12 felipensp