Skip to content

toml: add compile error when passing encode/1 types of T != struct#24443

Merged
spytheman merged 1 commit into
vlang:masterfrom
larpon:toml/give-compile-error-on-encode-type-other-than-struct
May 10, 2025
Merged

toml: add compile error when passing encode/1 types of T != struct#24443
spytheman merged 1 commit into
vlang:masterfrom
larpon:toml/give-compile-error-on-encode-type-other-than-struct

Conversation

@larpon

@larpon larpon commented May 9, 2025

Copy link
Copy Markdown
Contributor

fixes #24435 ... kind of. The C error should still be fixed somehow IMO and maybe the MRE in #24435 is actually valuable. I can reproduce something similar with e.g. (without importing toml):

module main

type Any = string | int

fn (a Any) to_toml() string {
	return match a {
		string {
			'TOML string'
		}
		int {
			'TOML int'
		}
	}
}

fn (m map[string]Any) to_toml() string {
	mut t := ''
	for _, v in m {
		t += v.to_toml() + ','
	}
	return t
}

fn main() {
	mut doc := map[string]Any{}
	doc['key'] = Any('value')

	// Try to encode it - this is where the bug occurs
	toml_content := encode(doc)

	println(toml_content)
}

fn encode[T](typ T) string {
	$for method in T.methods {
		$if method.name == 'to_toml' {
			return typ.$method()
		}
	}
	mp := encode_struct[T](typ)
	return mp.to_toml()
}

fn encode_struct[T](typ T) map[string]Any {
	mut mp := map[string]Any{}
	$for field in T.fields {
		mut skip := false
		mut field_name := field.name
		for attr in field.attrs {
			if attr == 'skip' {
				skip = true
				break
			}
			if attr.starts_with('toml:') {
				field_name = attr.all_after(':').trim_space()
			}
		}
		if !skip {
			mp[field_name] = to_any(typ.$(field.name))
		}
	}
	return mp
}

@huly-for-github

Copy link
Copy Markdown

Connected to Huly®: V_0.6-22814

@spytheman spytheman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you 🙇🏻‍♂️ .

@spytheman spytheman merged commit 031fce4 into vlang:master May 10, 2025
64 checks passed
@larpon larpon deleted the toml/give-compile-error-on-encode-type-other-than-struct branch May 10, 2025 08:57
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.

TOML encoding C compilation error

2 participants