Commit bea791b639

Evan Haas <evan@lagerdata.com>
2021-01-18 20:03:14
translate-c: fix variadic function calls
1702b413 introduced a bug with variadic function calls - trying to access the paramType of non-existent parameters.
1 parent 58344e0
Changed files (2)
src/translate_c.zig
@@ -3130,12 +3130,15 @@ fn transCallExpr(rp: RestorePoint, scope: *Scope, stmt: *const clang.CallExpr, r
         if (fn_ty) |ty| {
             switch (ty) {
                 .Proto => |fn_proto| {
-                    const param_qt = fn_proto.getParamType(@intCast(c_uint, i));
-                    if (isBoolRes(call_param) and cIsNativeInt(param_qt)) {
-                        const builtin_node = try rp.c.createBuiltinCall("@boolToInt", 1);
-                        builtin_node.params()[0] = call_param;
-                        builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")");
-                        call_param = &builtin_node.base;
+                    const param_count = fn_proto.getNumParams();
+                    if (i < param_count) {
+                        const param_qt = fn_proto.getParamType(@intCast(c_uint, i));
+                        if (isBoolRes(call_param) and cIsNativeInt(param_qt)) {
+                            const builtin_node = try rp.c.createBuiltinCall("@boolToInt", 1);
+                            builtin_node.params()[0] = call_param;
+                            builtin_node.rparen_token = try appendToken(rp.c, .RParen, ")");
+                            call_param = &builtin_node.base;
+                        }
                     }
                 },
                 else => {},
test/run_translated_c.zig
@@ -737,4 +737,13 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {
         \\    return 0;
         \\}
     , "");
+
+    cases.add("Variadic function call",
+        \\#define _NO_CRT_STDIO_INLINE 1
+        \\#include <stdio.h>
+        \\int main(void) {
+        \\    printf("%d %d\n", 1, 2);
+        \\    return 0;
+        \\}
+    , "1 2" ++ nl);
 }