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

v: Improve C var args interop #21812

Merged
merged 7 commits into from
Jul 8, 2024
Merged

Conversation

felipensp
Copy link
Member

@felipensp felipensp commented Jul 6, 2024

This PR:

  • Introduce simple ... syntax for function declaration (to use C var args)
  • Makes possible to declare C.va_list{} without initialization.
@[typedef]
struct C.va_list {}
fn C.va_start(voidptr, voidptr)
fn C.va_end(voidptr)

fn C.vfprintf(&C.FILE, &char, C.va_list) int

fn t2(fmt voidptr, ...) {
	ap := C.va_list{}
	C.va_start(ap, fmt)
	C.vfprintf(C.stderr, fmt, ap)
	C.va_end(ap)
}

fn main() {
	a := 1
	b := 2.5
	t2(c'%s : %d : %.2f\n', c'foo', a, b)
}

Outputs foo : 1 : 2.50

vlib/v/gen/c/cheaders.v Outdated Show resolved Hide resolved
@felipensp felipensp marked this pull request as ready for review July 7, 2024 02:27
@spytheman
Copy link
Member

Excellent work, but it misses a test, and it does not fix #20636 yet (which uses also va_arg, and v translate does not handle well neither va_start, va_end nor va_arg ... va_arg also accepts a type name as its second argument, which can not be modeled currently in V, except perhaps as a generic).

I suggest adding a test .vv file, in vlib/v/gen/c/testdata/, that includes a .c file containing the definition of a variadic function printing its arguments, then declaring and calling it in the .vv file, and having an .out file with the printed output.

Then ./v vlib/v/gen/c/coutput_test.v will pick up the file and check that it continues to work locally and on the CIs.

@spytheman
Copy link
Member

spytheman commented Jul 7, 2024

The current example can also be copy/pasted as a _keep.vv file in vlib/v/fmt/tests/, to ensure that vfmt will continue to handle it (testing both the parser and the output of vfmt).

@spytheman spytheman merged commit 66ea826 into vlang:master Jul 8, 2024
76 checks passed
@felipensp felipensp deleted the feat_varargs branch October 15, 2024 11:33
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.

2 participants