Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cgen: fix function generated code when returning from match #20263

Merged
merged 3 commits into from
Dec 25, 2023

Conversation

felipensp
Copy link
Member

Fix #20260 (it requires fix for #20169 to be applied to work the test case below)

import x.json2

fn maybe_map_map[T, U, X, Y](m map[T]U, f fn(T, U) !(X, Y) ) !map[X]Y {
	mut r := map[X]Y{}
	for k, v in m {
		nk, nv := f(k, v)!
		r[nk] = nv
	}
	return r
}
type Snowflake = int
struct User {
	id Snowflake
	name string
}
fn User.parse(j json2.Any) !User {
	match j {
		map[string]json2.Any {
			return User{
				id: j['id']! as int
				name: j['name']! as string
			}
		}
		else {
			return error('expected user to be object, got ${j.type_name()}')
		}
	}
}
struct Resolved {
	users ?map[Snowflake]User
}
fn Resolved.parse(j json2.Any) !Resolved {
	match j {
		map[string]json2.Any {
			return Resolved{
				users: if m := j['users'] {
					maybe_map_map[string, json2.Any, Snowflake, User](m as map[string]json2.Any, fn (k string, v json2.Any) !(Snowflake, User) {
						return Snowflake(k.int()), User.parse(v)!
					})!
				} else {
					none
				}
			}
		}
		else {
			panic('asdadsd')
		}
	}
}
fn main() {
	println('asd')
	Resolved.parse({
		'0': json2.Any('1')
		'2': '3'
		'a4': 5
		'6': '7'
	}) or {
		assert err.msg() == 'expected user to be object, got string'
		return
	}
	assert false, 'It should return error'
}

@felipensp felipensp marked this pull request as ready for review December 25, 2023 14:07
Copy link
Member

@spytheman spytheman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent work.

@spytheman spytheman merged commit 5a9800b into vlang:master Dec 25, 2023
54 checks passed
@felipensp felipensp deleted the fix_return_gen_code branch December 25, 2023 17:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Cgen incorrectly declares functions in output
2 participants