v icon indicating copy to clipboard operation
v copied to clipboard

Error handling, compile error

Open eptx opened this issue 11 months ago • 2 comments

Describe the bug

Followed compile warnings until compile error.

Reproduction Steps

With this code:

import x.json2
fn main() {
    json_str := '{"data": [{"name":"bob"}, {"name":"tom"}]}'
    decoded := json2.raw_decode(json_str) or {
        eprintln('Failed to decode JSON: $err')
        return
    }
    data_arr := decoded.as_map()['data']!.arr() // 1) added the ! here based on warning
    names := data_arr.map(fn (item json2.Any) !string { // 3) added the ! here based on warning and got compile error
        return item.as_map()['name']!.str() // 2) added the ! here based on warning
    })
    println(names)
}

I got a couple warnings to use 'or {}'. So I kept adding '!' until I got:

 warning: expression result unused [-Wunused-value]
  (*(string*)_t3.data);
   ^~~~~~~~~~~~~~~~~~
1 warning and 1 error generated.
...
==================
(Use `v -cg` to print the entire error message)

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

Expected Behavior

print names parsed from json

Current Behavior

compile error

Possible Solution

No response

Additional Information/Context

No response

V version

V 0.4.4 fb93828.f789874

Environment details (OS name and version, etc.)

V full version: V 0.4.4 fb93828.f789874 OS: macos, macOS, 14.1.1, 23B81 Processor: 12 cpus, 64bit, little endian, Apple M2 Max

[!NOTE] You can use the 👍 reaction to increase the issue's priority for developers.

Please note that only the 👍 reaction to the issue itself counts as a vote. Other reactions and those to comments will not be taken into account.

eptx avatar Mar 08 '24 20:03 eptx

Thanks for the issue.

I think that the compiler should not have allowed fn (item json2.Any) !string to be used as an argument of .map(), since a result value has to be handled right away, not stored in an array. It should have been a checker error, instead of a cgen one.

A fixed version of the code above may look like this:

import x.json2
fn main() {
    json_str := '{"data": [{"name":"bob"}, {"name":"tom"}]}'
    decoded := json2.raw_decode(json_str) or {
        eprintln('Failed to decode JSON: $err')
        return
    }
    data_arr := decoded.as_map()['data']!.arr()
    names := data_arr.map(fn (item json2.Any) string {
        return item.as_map()['name'] or {''}.str()
    })
    println(names)
}

spytheman avatar Mar 09 '24 07:03 spytheman

i think it should require ! on map() result if callback returns Result's, otherwise everyone will make their maybe_map/``maybe_map_map` functions

MCausc78 avatar Mar 11 '24 19:03 MCausc78