Thanks for using Compiler Explorer
Sponsors
Jakt
C++
Ada
Algol68
Analysis
Android Java
Android Kotlin
Assembly
C
C3
Carbon
C with Coccinelle
C++ with Coccinelle
C++ (Circle)
CIRCT
Clean
Clojure
CMake
CMakeScript
COBOL
C++ for OpenCL
MLIR
Cppx
Cppx-Blue
Cppx-Gold
Cpp2-cppfront
Crystal
C#
CUDA C++
D
Dart
Elixir
Erlang
Fortran
F#
GLSL
Go
Haskell
HLSL
Helion
Hook
Hylo
IL
ispc
Java
Julia
Kotlin
LLVM IR
LLVM MIR
Modula-2
Mojo
Nim
Numba
Nix
Objective-C
Objective-C++
OCaml
Odin
OpenCL C
Pascal
Pony
PTX
Python
Racket
Raku
Ruby
Rust
Sail
Snowball
Scala
Slang
Solidity
Spice
SPIR-V
Swift
LLVM TableGen
Toit
Triton
TypeScript Native
V
Vala
Visual Basic
Vyper
WASM
Yul (Solidity IR)
Zig
Javascript
GIMPLE
Ygen
sway
zig source #1
Output
Compile to binary object
Link to binary
Execute the code
Intel asm syntax
Demangle identifiers
Verbose demangling
Filters
Unused labels
Library functions
Directives
Comments
Horizontal whitespace
Debug intrinsics
Compiler
zig 0.10.0
zig 0.11.0
zig 0.12.0
zig 0.12.1
zig 0.13.0
zig 0.14.0
zig 0.14.1
zig 0.15.1
zig 0.15.2
zig 0.2.0
zig 0.3.0
zig 0.4.0
zig 0.5.0
zig 0.6.0
zig 0.7.0
zig 0.7.1
zig 0.8.0
zig 0.9.0
zig trunk
Options
Source code
const std = @import("std"); const hex_print_bits = 64; const hex_print_t = std.meta.Int(.unsigned, hex_print_bits); const hex_print_nibbles = @divExact(hex_print_bits, 4); pub noinline fn printCharacter(ch: u8) void { asm volatile("" :: [blargh] "r" (ch)); } noinline fn printString(str: [*:0]const u8) void { if (str[0] != 0) { printCharacter(str[0]); return @call(.{ .modifier = .always_tail }, printString, .{str + 1}); } } const hex_chars: [*]const u8 = "0123456789ABCDEF"; noinline fn printRuntimeValueAsZeroPaddedHex(val: hex_print_t) void { var i: u6 = hex_print_nibbles - 1; while (true) : (i -= 1) { const v = @truncate(u4, val >> (4 * i)); printCharacter(hex_chars[v]); if (i == 0) break; } } fn comptimeValToZeroPaddedHexString(in_val: anytype) [hex_print_nibbles]u8 { const val = @intCast(hex_print_t, in_val); var i: u6 = 0; var result: [hex_print_nibbles]u8 = undefined; while (i < hex_print_nibbles) : (i += 1) { result[i] = hex_chars[@truncate(u4, val >> ((hex_print_nibbles - i - 1) * 4))]; } return result; } fn formatMatches(fmt: []const u8, idx: usize, to_match: []const u8) callconv(.Inline) bool { const curr_fmt = fmt[idx..]; return std.mem.startsWith(u8, curr_fmt, to_match); } fn lengthOfIntAsString(num: anytype, comptime base: comptime_int) usize { if (num < base) return 1; const rest = num / base; return lengthOfIntAsString(rest, base) + 1; } fn comptimeValToString(val: anytype, comptime base: comptime_int) [lengthOfIntAsString(val, base)]u8 { const current = hex_chars[val % base]; const rest = val / base; if (rest == 0) return [_]u8{current}; return comptimeValToString(rest, base) ++ [_]u8{current}; } noinline fn printRuntimeValue(val: usize, comptime base: comptime_int) void { const rest = val / base; if (rest != 0) printRuntimeValue(rest, base); return printCharacter(hex_chars[val % base]); } fn putComptimeStr(comptime str: [:0]const u8) callconv(.Inline) void { if (comptime (str.len == 1)) { printCharacter(str[0]); } if (comptime (str.len > 1)) { printString(str.ptr); } } noinline fn defaultFormatStruct(value: anytype) void { const arg_fields = @typeInfo(@TypeOf(value.*)).Struct.fields; comptime var current_fmt: [:0]const u8 = @typeName(@TypeOf(value.*)) ++ "{{ "; inline for (arg_fields) |field, i| { current_fmt = current_fmt ++ "." ++ field.name ++ " = "; switch (@typeInfo(field.field_type)) { .Int => doFmtNoEndl(current_fmt ++ "{d}", .{@field(value.*, field.name)}), .Struct => doFmtNoEndl(current_fmt ++ "{}", .{@field(value.*, field.name)}), else => @compileError("No idea how to format this struct field type: '" ++ @typeName(field.field_type) ++ "'!"), } current_fmt = if (i == current_fmt.len - 1) "" else ", "; } current_fmt = current_fmt ++ " }}"; doFmtNoEndl(current_fmt, .{}); } pub fn doFmtNoEndl(comptime fmt: []const u8, args: anytype) void { comptime var fmt_idx = 0; comptime var arg_idx = 0; comptime var current_str: [:0]const u8 = ""; const arg_fields = @typeInfo(@TypeOf(args)).Struct.fields; @setEvalBranchQuota(9999999); inline while (fmt_idx < fmt.len) { if (comptime formatMatches(fmt, fmt_idx, "{{")) { current_str = current_str ++ [_]u8{'{'}; fmt_idx += 2; } else if (comptime formatMatches(fmt, fmt_idx, "}}")) { current_str = current_str ++ [_]u8{'}'}; fmt_idx += 2; } else if (comptime formatMatches(fmt, fmt_idx, "{0X}")) { const value = @field(args, arg_fields[arg_idx].name); if (arg_fields[arg_idx].is_comptime) { current_str = current_str ++ comptime comptimeValToZeroPaddedHexString(value); } else { printString(current_str.ptr); current_str = ""; printRuntimeValueAsZeroPaddedHex(value); } fmt_idx += 4; arg_idx += 1; } else if (comptime formatMatches(fmt, fmt_idx, "{X}")) { const value = @field(args, arg_fields[arg_idx].name); if (arg_fields[arg_idx].is_comptime) { current_str = current_str ++ comptime comptimeValToString(value, 16); } else { printString(current_str.ptr); current_str = ""; printRuntimeValue(value, 16); } fmt_idx += 3; arg_idx += 1; } else if (comptime formatMatches(fmt, fmt_idx, "{d}")) { const value = @field(args, arg_fields[arg_idx].name); if (arg_fields[arg_idx].is_comptime) { current_str = current_str ++ comptime comptimeValToString(value, 10); } else { printString(current_str.ptr); current_str = ""; printRuntimeValue(value, 10 ); } fmt_idx += 3; arg_idx += 1; } else if (comptime formatMatches(fmt, fmt_idx, "{e}")) { const value = @field(args, arg_fields[arg_idx].name); switch (@typeInfo(@TypeOf(value))) { .Enum => current_str = current_str ++ @typeName(@TypeOf(value)), else => {}, } current_str = current_str ++ "."; if (arg_fields[arg_idx].is_comptime) { current_str = current_str ++ comptime @tagName(value); } else { printString(current_str.ptr); current_str = ""; printString(@tagName(value)); } fmt_idx += 3; arg_idx += 1; } else if (comptime formatMatches(fmt, fmt_idx, "{s}")) { const value = @field(args, arg_fields[arg_idx].name); if (arg_fields[arg_idx].is_comptime) { current_str = current_str ++ comptime value; } else { printString(current_str.ptr); current_str = ""; // TODO: Different paths depending on the string type: [*:0]const u8, []const u8, ... // For now we just assume [*:0]const u8 printString(value); } fmt_idx += 3; arg_idx += 1; } else if (comptime formatMatches(fmt, fmt_idx, "{c}")) { const value = @field(args, arg_fields[arg_idx].name); if (arg_fields[arg_idx].is_comptime) { current_str = current_str ++ comptime [_]u8{value}; } else { printString(current_str.ptr); current_str = ""; printCharacter(value); } fmt_idx += 3; arg_idx += 1; } else if (comptime formatMatches(fmt, fmt_idx, "{}")) { const value = @field(args, arg_fields[arg_idx].name); printString(current_str.ptr); current_str = ""; if (comptime @hasDecl(@TypeOf(value), "format")) { @call(.{ .modifier = .never_inline }, value.format, .{}); } else { defaultFormatStruct(&value); } fmt_idx += 2; arg_idx += 1; } else if (comptime formatMatches(fmt, fmt_idx, "{")) { @compileError("Unknown format specifier: '" ++ [_]u8{fmt[fmt_idx + 1]} ++ "'"); } else { current_str = current_str ++ [_]u8{fmt[fmt_idx]}; fmt_idx += 1; } } putComptimeStr(current_str); if (arg_idx < arg_fields.len) { @compileError("Unused fmt arguments!"); } } pub fn doFmt(comptime fmt: []const u8, args: anytype) callconv(.Inline) void { return doFmtNoEndl(fmt ++ "\n", args); } fn rdrand() u64 { return asm volatile ("rdrand %[result]" : [result] "=r" (-> u64) ); } const TestStructWithFormat = struct { value: u64, pub const format = if (use_std) (struct { pub fn f(self: *const TestStructWithFormat, fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; _ = fmt; return writer.print("{{ .value = {0X} }}", .{self.value}); } }.f) else (struct { pub fn f(self: *const TestStructWithFormat) void { doFmtNoEndl("{{ .value = {0X} }}", .{self.value}); } }.f); }; const TestEnum = enum { World, }; const TestStructWithoutFormat = struct { value: u64, oobooii: TestStructWithFormat = .{ .value = 5 }, }; const use_std = false; const test_log = if (use_std) std.log.err else doFmt; export fn example1() void { test_log("Hello, {e}! This is my favourite number: {{{X}}}", .{ TestEnum.World, rdrand() }); } export fn example2() void { test_log("Hello! This is my favourite struct: {}", .{TestStructWithoutFormat{ .value = rdrand() }}); } export fn example3() void { test_log("Hello! This is a very nice number: {d}!", .{69}); }
Become a Patron
Sponsor on GitHub
Donate via PayPal
Compiler Explorer Shop
Source on GitHub
Mailing list
Installed libraries
Wiki
Report an issue
How it works
Contact the author
CE on Mastodon
CE on Bluesky
Statistics
Changelog
Version tree