{#syntax#}@Type(.Opaque){#endsyntax#} creates a new type with an unknown (but non-zero) size and alignment.
From 12a7dedb1f1ce34b16993d33aa97d7b78d5d5ca2 Mon Sep 17 00:00:00 2001
From: Ryan Liptak
The code samples in this document are compiled and tested as part of the main test suite of Zig. +
+This HTML document depends on no external files, so you can use it offline.
@@ -236,10 +238,89 @@ pub fn main() !void { } {#code_end#}
- Usually you don't want to write to stdout. You want to write to stderr, and you
- don't care if it fails. For that you can use a simpler API:
+ The Zig code sample above demonstrates one way to create a program that will output Hello, world!.
+ The code sample shows the contents of a file named hello.zig. Files storing Zig
+ source code are {#link|UTF-8 encoded|Source Encoding#} text files. The files storing
+ Zig source code are usually named with the .zig extension.
+
+ Following the hello.zig Zig code sample, the {#link|Zig Build System#} is used
+ to build an executable program from the hello.zig source code. Then, the
+ hello program is executed showing its output Hello, world!. The
+ lines beginning with $ represent command line prompts and a command.
+ Everything else is program output.
+
+ The code sample begins by adding Zig's Standard Library to the build using the {#link|@import#} builtin function.
+ The {#syntax#}@import("std"){#endsyntax#} function call creates a structure to represent the Standard Library.
+ The code then makes a {#link|top-level declaration|Global Variables#} of a
+ {#link|constant identifier|Assignment#}, named std, for easy access to
+ Zig's standard library.
+
+ Next, a {#link|public function|Functions#}, {#syntax#}pub fn{#endsyntax#}, named main
+ is declared. The main function is necessary because it tells the Zig compiler where the start of
+ the program exists. Programs designed to be executed will need a {#syntax#}pub fn main{#endsyntax#} function.
+ For more advanced Zig use cases, Zig offers other features to inform the compiler where the start of
+ the program exists. Libraries, on the other hand, do not need a main function because
+ library code is usually called by other programs.
+
+ A function is a block of any number of statements and expressions that, as a whole, perform a task. + Functions may or may not return data after they are done performing their task. +
+
+ In the hello.zig code sample, the main function is declared
+ with the {#syntax#}!void{#endsyntax#} return type. This return type tells the Zig compiler,
+ and other people reading the code, the function will not return a value and it might fail.
+ The {#syntax#}!{#endsyntax#} (bang, exclamation mark) before the {#syntax#}void{#endsyntax#}
+ {#link|type|Primitive Types#} is what tells the Zig compiler an {#link|error|Errors#} might
+ occur. The {#syntax#}void{#endsyntax#} return type tells the Zig compiler the main
+ function will not return a value.
+
+ In Zig, a function's block of statements and expressions are surrounded by { and
+ } curly-braces. Inside of the main function are expressions that perform
+ the task of outputting Hello, world! to standard output.
+
+ First, a constant identifier, stdout, is initialized to represent the standard output
+ stream. Then, the program tries to print the Hello, world! message to the standard output
+ stream.
+
+ Functions sometimes need information to perform their task. In Zig, information is passed
+ to functions between open ( and close ) parenthesis placed after
+ the function's name. The information passed to functions are its arguments. When there are
+ multiple arguments passed to a function, they are separated by commas ,.
+
+ The two arguments passed to the stdout.print() function, "Hello, {}!\n"
+ and .{"world"}, are evaluated at {#link|compile-time|comptime#}. The code sample is
+ purposely written to show how to perform {#link|string|String Literals and Character Literals#}
+ substitution in the print function. The curly-braces inside of the first argument
+ are substituted with the compile-time known value inside of the second argument
+ (known as an {#link|anonymous struct literal|Anonymous Struct Literals#}). The \n
+ inside of the double-quotes of the first argument is the {#link|escape sequence|Escape Sequences#} for the
+ newline character. The {#link|try#} expression evaluates the result of stdout.print.
+ If the result is an error, then the {#syntax#}try{#endsyntax#} expression will return from
+ main with the error. Otherwise, the program will continue. In this case, there are no
+ more statements or expressions left to execute in the main function, so the program exits.
+
+ In Zig, the standard output stream's print function is allowed to fail because
+ it is actually a function defined for a generic output stream. Consider a generic output stream that
+ represents writing data to a file and the disk is full; a write to the file will fail. However,
+ we typically do not expect writing text to the standard output stream to fail. To avoid having
+ to handle the failure case of printing to a standard output, you can use alternate functions: the
+ std.log function for proper logging or the std.debug.print function.
+ This documentation will use the latter option to print to standard error (stderr) and silently
+ return on failure. The next code sample, hello_again.zig demonstrates the use of
+ std.debug.print.
+
- Note that you can leave off the {#syntax#}!{#endsyntax#} from the return type because {#syntax#}print{#endsyntax#} cannot fail.
+ Note that you can leave off the {#syntax#}!{#endsyntax#} from the return type because std.debug.print cannot fail.
In the
In Zig, the standard output stream's
Functions sometimes need information to perform their task. In Zig, information is passed
to functions between open
From e57458a94f677c54ba3ff6698831312e622e8b2b Mon Sep 17 00:00:00 2001
From: Paul
A function is a block of any number of statements and expressions that, as a whole, perform a task.
- Functions may or may not return data after they are done performing their task.
+ Functions may or may not return data after they are done performing their task. If a function
+ cannot perform its task, it might return an error. Zig makes all of this explicit.
In the
+ Note to experienced programmers: Zig also has the boolean {#link|operator|Operators#} {#syntax#}!a{#endsyntax#}
+ where {#syntax#}a{#endsyntax#} is a value of type {#syntax#}bool{#endsyntax#}. Error union types contain the
+ name of the type in the syntax: {#syntax#}!{#endsyntax#}
In Zig, a function's block of statements and expressions are surrounded by
- First, a constant identifier,
Functions sometimes need information to perform their task. In Zig, information is passed
@@ -310,14 +319,14 @@ pub fn main() !void {
more statements or expressions left to execute in the
- In Zig, the standard output stream's
- Function parameters can be declared with {#syntax#}var{#endsyntax#} in place of the type.
+ Function parameters can be declared with {#syntax#}anytype{#endsyntax#} in place of the type.
In this case the parameter types will be inferred when the function is called.
Use {#link|@TypeOf#} and {#link|@typeInfo#} to get information about the inferred type.
hello.zig code sample, the main function is declared
- with the {#syntax#}!void{#endsyntax#} return type. This return type tells the Zig compiler,
- and other people reading the code, the function will not return a value and it might fail.
+ with the {#syntax#}!void{#endsyntax#} return type. This return type tells the Zig compiler
+ and other people reading the code that the function will not return a value and it might fail.
The {#syntax#}!{#endsyntax#} (bang, exclamation mark) before the {#syntax#}void{#endsyntax#}
{#link|type|Primitive Types#} is what tells the Zig compiler an {#link|error|Errors#} might
occur. The {#syntax#}void{#endsyntax#} return type tells the Zig compiler the main
From 656b640e79e8cd391a046bb69713bffc3e0ff7b3 Mon Sep 17 00:00:00 2001
From: Paul print function is allowed to fail because
it is actually a function defined for a generic output stream. Consider a generic output stream that
- represents writing data to a file and the disk is full; a write to the file will fail. However,
+ represents writing data to a file. When the disk is full, a write to the file will fail. However,
we typically do not expect writing text to the standard output stream to fail. To avoid having
to handle the failure case of printing to a standard output, you can use alternate functions: the
std.log function for proper logging or the std.debug.print function.
From 50df1334f35411e0dbf12624dab68667a4e7a6ac Mon Sep 17 00:00:00 2001
From: Paul ( and close ) parenthesis placed after
- the function's name. The information passed to functions are its arguments. When there are
+ the function's name. This information is also known as arguments. When there are
multiple arguments passed to a function, they are separated by commas ,.
main
is declared. The main function is necessary because it tells the Zig compiler where the start of
the program exists. Programs designed to be executed will need a {#syntax#}pub fn main{#endsyntax#} function.
- For more advanced Zig use cases, Zig offers other features to inform the compiler where the start of
+ For more advanced use cases, Zig offers other features to inform the compiler where the start of
the program exists. Libraries, on the other hand, do not need a main function because
library code is usually called by other programs.
hello.zig code sample, the main function is declared
- with the {#syntax#}!void{#endsyntax#} return type. This return type tells the Zig compiler
- and other people reading the code that the function will not return a value and it might fail.
- The {#syntax#}!{#endsyntax#} (bang, exclamation mark) before the {#syntax#}void{#endsyntax#}
- {#link|type|Primitive Types#} is what tells the Zig compiler an {#link|error|Errors#} might
- occur. The {#syntax#}void{#endsyntax#} return type tells the Zig compiler the main
- function will not return a value.
+ with the {#syntax#}!void{#endsyntax#} return type. This return type is known as an {#link|Error Union Type#}.
+ This syntax tells the Zig compiler that the function will either return an
+ error or a value. An error union type combines an {#link|Error Set Type#} and a {#link|Primitive Type|Primitive Types#}.
+ The full form of an error union type is
+ <error set type>{#syntax#}!{#endsyntax#}<primitive type>. In the code
+ sample, the error set type is not explicitly written on the left side of the {#syntax#}!{#endsyntax#} operator.
+ When written this way, the error set type is a special kind of error union type that has an
+ {#link|inferred error set type|Inferred Error Sets#}. The {#syntax#}void{#endsyntax#} after the {#syntax#}!{#endsyntax#} operator
+ tells the compiler that the function will not return a value under normal circumstances (i.e. no errors occur).
+ <primitive type>.
{ and
@@ -286,9 +295,9 @@ pub fn main() !void {
the task of outputting Hello, world! to standard output.
stdout, is initialized to represent the standard output
- stream. Then, the program tries to print the Hello, world! message to the standard output
- stream.
+ First, a constant identifier, stdout, is initialized to represent standard output's
+ writer. Then, the program tries to print the Hello, world!
+ message to standard output.
main function, so the program exits.
print function is allowed to fail because
- it is actually a function defined for a generic output stream. Consider a generic output stream that
- represents writing data to a file. When the disk is full, a write to the file will fail. However,
- we typically do not expect writing text to the standard output stream to fail. To avoid having
- to handle the failure case of printing to a standard output, you can use alternate functions: the
+ In Zig, the standard output writer's print function is allowed to fail because
+ it is actually a function defined as part of a generic Writer. Consider a generic Writer that
+ represents writing data to a file. When the disk is full, a write to the file will fail.
+ However, we typically do not expect writing text to the standard output to fail. To avoid having
+ to handle the failure case of printing to standard output, you can use alternate functions: the
std.log function for proper logging or the std.debug.print function.
- This documentation will use the latter option to print to standard error (stderr) and silently
- return on failure. The next code sample, hello_again.zig demonstrates the use of
+ This documentation will use the latter option to print to standard error (stderr) and silently return
+ on failure. The next code sample, hello_again.zig demonstrates the use of
std.debug.print.
{#syntax#}@alignCast(comptime alignment: u29, ptr: var) var{#endsyntax#}
+ {#syntax#}@alignCast(comptime alignment: u29, ptr: anytype) anytype{#endsyntax#}
{#syntax#}ptr{#endsyntax#} can be {#syntax#}*T{#endsyntax#}, {#syntax#}fn(){#endsyntax#}, {#syntax#}?*T{#endsyntax#}, {#syntax#}?fn(){#endsyntax#}, or {#syntax#}[]T{#endsyntax#}. It returns the same type as {#syntax#}ptr{#endsyntax#} @@ -6723,7 +6723,7 @@ comptime { {#header_close#} {#header_open|@asyncCall#} -
{#syntax#}@asyncCall(frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8, result_ptr, function_ptr, args: var) anyframe->T{#endsyntax#}
+ {#syntax#}@asyncCall(frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8, result_ptr, function_ptr, args: anytype) anyframe->T{#endsyntax#}
{#syntax#}@asyncCall{#endsyntax#} performs an {#syntax#}async{#endsyntax#} call on a function pointer, which may or may not be an {#link|async function|Async Functions#}. @@ -6811,7 +6811,7 @@ fn func(y: *i32) void {
{#header_close#} {#header_open|@bitCast#} -{#syntax#}@bitCast(comptime DestType: type, value: var) DestType{#endsyntax#}
+ {#syntax#}@bitCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}
Converts a value of one type to another type.
@@ -6932,7 +6932,7 @@ fn func(y: *i32) void { {#header_close#} {#header_open|@call#} -{#syntax#}@call(options: std.builtin.CallOptions, function: var, args: var) var{#endsyntax#}
+ {#syntax#}@call(options: std.builtin.CallOptions, function: anytype, args: anytype) anytype{#endsyntax#}
Calls a function, in the same way that invoking an expression with parentheses does:
@@ -7279,7 +7279,7 @@ test "main" { {#header_close#} {#header_open|@enumToInt#} -{#syntax#}@enumToInt(enum_or_tagged_union: var) var{#endsyntax#}
+ {#syntax#}@enumToInt(enum_or_tagged_union: anytype) anytype{#endsyntax#}
Converts an enumeration value into its integer tag type. When a tagged union is passed, the tag value is used as the enumeration value. @@ -7314,7 +7314,7 @@ test "main" { {#header_close#} {#header_open|@errorToInt#} -
{#syntax#}@errorToInt(err: var) std.meta.IntType(false, @sizeOf(anyerror) * 8){#endsyntax#}
+ {#syntax#}@errorToInt(err: anytype) std.meta.IntType(false, @sizeOf(anyerror) * 8){#endsyntax#}
Supports the following types:
@@ -7334,7 +7334,7 @@ test "main" { {#header_close#} {#header_open|@errSetCast#} -{#syntax#}@errSetCast(comptime T: DestType, value: var) DestType{#endsyntax#}
+ {#syntax#}@errSetCast(comptime T: DestType, value: anytype) DestType{#endsyntax#}
Converts an error value from one error set to another error set. Attempting to convert an error which is not in the destination error set results in safety-protected {#link|Undefined Behavior#}. @@ -7342,7 +7342,7 @@ test "main" { {#header_close#} {#header_open|@export#} -
{#syntax#}@export(target: var, comptime options: std.builtin.ExportOptions) void{#endsyntax#}
+ {#syntax#}@export(target: anytype, comptime options: std.builtin.ExportOptions) void{#endsyntax#}
Creates a symbol in the output object file.
@@ -7387,7 +7387,7 @@ export fn @"A function name that is a complete sentence."() void {} {#header_close#} {#header_open|@field#} -{#syntax#}@field(lhs: var, comptime field_name: []const u8) (field){#endsyntax#}
+ {#syntax#}@field(lhs: anytype, comptime field_name: []const u8) (field){#endsyntax#}
Performs field access by a compile-time string.
{#code_begin|test#} @@ -7421,7 +7421,7 @@ test "field access by string" { {#header_close#} {#header_open|@floatCast#} -{#syntax#}@floatCast(comptime DestType: type, value: var) DestType{#endsyntax#}
+ {#syntax#}@floatCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}
Convert from one float type to another. This cast is safe, but may cause the numeric value to lose precision. @@ -7429,7 +7429,7 @@ test "field access by string" { {#header_close#} {#header_open|@floatToInt#} -
{#syntax#}@floatToInt(comptime DestType: type, float: var) DestType{#endsyntax#}
+ {#syntax#}@floatToInt(comptime DestType: type, float: anytype) DestType{#endsyntax#}
Converts the integer part of a floating point number to the destination type.
@@ -7455,7 +7455,7 @@ test "field access by string" { {#header_close#} {#header_open|@Frame#} -{#syntax#}@Frame(func: var) type{#endsyntax#}
+ {#syntax#}@Frame(func: anytype) type{#endsyntax#}
This function returns the frame type of a function. This works for {#link|Async Functions#} as well as any function without a specific calling convention. @@ -7581,7 +7581,7 @@ test "@hasDecl" { {#header_close#} {#header_open|@intCast#} -
{#syntax#}@intCast(comptime DestType: type, int: var) DestType{#endsyntax#}
+ {#syntax#}@intCast(comptime DestType: type, int: anytype) DestType{#endsyntax#}
Converts an integer to another integer while keeping the same numerical value. Attempting to convert a number which is out of range of the destination type results in @@ -7622,7 +7622,7 @@ test "@hasDecl" { {#header_close#} {#header_open|@intToFloat#} -
{#syntax#}@intToFloat(comptime DestType: type, int: var) DestType{#endsyntax#}
+ {#syntax#}@intToFloat(comptime DestType: type, int: anytype) DestType{#endsyntax#}
Converts an integer to the closest floating point representation. To convert the other way, use {#link|@floatToInt#}. This cast is always safe.
@@ -7773,7 +7773,7 @@ test "@wasmMemoryGrow" { {#header_close#} {#header_open|@ptrCast#} -{#syntax#}@ptrCast(comptime DestType: type, value: var) DestType{#endsyntax#}
+ {#syntax#}@ptrCast(comptime DestType: type, value: anytype) DestType{#endsyntax#}
Converts a pointer of one type to a pointer of another type.
@@ -7784,7 +7784,7 @@ test "@wasmMemoryGrow" { {#header_close#} {#header_open|@ptrToInt#} -{#syntax#}@ptrToInt(value: var) usize{#endsyntax#}
+ {#syntax#}@ptrToInt(value: anytype) usize{#endsyntax#}
Converts {#syntax#}value{#endsyntax#} to a {#syntax#}usize{#endsyntax#} which is the address of the pointer. {#syntax#}value{#endsyntax#} can be one of these types:
@@ -8042,7 +8042,7 @@ test "@setRuntimeSafety" { {#header_close#} {#header_open|@splat#} -{#syntax#}@splat(comptime len: u32, scalar: var) std.meta.Vector(len, @TypeOf(scalar)){#endsyntax#}
+ {#syntax#}@splat(comptime len: u32, scalar: anytype) std.meta.Vector(len, @TypeOf(scalar)){#endsyntax#}
Produces a vector of length {#syntax#}len{#endsyntax#} where each element is the value {#syntax#}scalar{#endsyntax#}: @@ -8088,7 +8088,7 @@ fn doTheTest() void { {#code_end#} {#header_close#} {#header_open|@sqrt#} -
{#syntax#}@sqrt(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@sqrt(value: anytype) @TypeOf(value){#endsyntax#}
Performs the square root of a floating point number. Uses a dedicated hardware instruction when available. @@ -8099,7 +8099,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@sin#} -{#syntax#}@sin(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@sin(value: anytype) @TypeOf(value){#endsyntax#}
Sine trigometric function on a floating point number. Uses a dedicated hardware instruction when available. @@ -8110,7 +8110,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@cos#} -{#syntax#}@cos(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@cos(value: anytype) @TypeOf(value){#endsyntax#}
Cosine trigometric function on a floating point number. Uses a dedicated hardware instruction when available. @@ -8121,7 +8121,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@exp#} -{#syntax#}@exp(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@exp(value: anytype) @TypeOf(value){#endsyntax#}
Base-e exponential function on a floating point number. Uses a dedicated hardware instruction when available. @@ -8132,7 +8132,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@exp2#} -{#syntax#}@exp2(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@exp2(value: anytype) @TypeOf(value){#endsyntax#}
Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction when available. @@ -8143,7 +8143,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@log#} -{#syntax#}@log(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@log(value: anytype) @TypeOf(value){#endsyntax#}
Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction when available. @@ -8154,7 +8154,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@log2#} -{#syntax#}@log2(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@log2(value: anytype) @TypeOf(value){#endsyntax#}
Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction when available. @@ -8165,7 +8165,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@log10#} -{#syntax#}@log10(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@log10(value: anytype) @TypeOf(value){#endsyntax#}
Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction when available. @@ -8176,7 +8176,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@fabs#} -{#syntax#}@fabs(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@fabs(value: anytype) @TypeOf(value){#endsyntax#}
Returns the absolute value of a floating point number. Uses a dedicated hardware instruction when available. @@ -8187,7 +8187,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@floor#} -{#syntax#}@floor(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@floor(value: anytype) @TypeOf(value){#endsyntax#}
Returns the largest integral value not greater than the given floating point number. Uses a dedicated hardware instruction when available. @@ -8198,7 +8198,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@ceil#} -{#syntax#}@ceil(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@ceil(value: anytype) @TypeOf(value){#endsyntax#}
Returns the largest integral value not less than the given floating point number. Uses a dedicated hardware instruction when available. @@ -8209,7 +8209,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@trunc#} -{#syntax#}@trunc(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@trunc(value: anytype) @TypeOf(value){#endsyntax#}
Rounds the given floating point number to an integer, towards zero. Uses a dedicated hardware instruction when available. @@ -8220,7 +8220,7 @@ fn doTheTest() void {
{#header_close#} {#header_open|@round#} -{#syntax#}@round(value: var) @TypeOf(value){#endsyntax#}
+ {#syntax#}@round(value: anytype) @TypeOf(value){#endsyntax#}
Rounds the given floating point number to an integer, away from zero. Uses a dedicated hardware instruction when available. @@ -8241,7 +8241,7 @@ fn doTheTest() void { {#header_close#} {#header_open|@tagName#} -
{#syntax#}@tagName(value: var) []const u8{#endsyntax#}
+ {#syntax#}@tagName(value: anytype) []const u8{#endsyntax#}
Converts an enum value or union value to a slice of bytes representing the name.
If the enum is non-exhaustive and the tag value does not map to a name, it invokes safety-checked {#link|Undefined Behavior#}.
@@ -8292,7 +8292,7 @@ fn List(comptime T: type) type { {#header_close#} {#header_open|@truncate#} -{#syntax#}@truncate(comptime T: type, integer: var) T{#endsyntax#}
+ {#syntax#}@truncate(comptime T: type, integer: anytype) T{#endsyntax#}
This function truncates bits from an integer type, resulting in a smaller
or same-sized integer type.
@@ -10214,7 +10214,7 @@ TopLevelDecl
/ (KEYWORD_export / KEYWORD_extern STRINGLITERALSINGLE?)? KEYWORD_threadlocal? VarDecl
/ KEYWORD_usingnamespace Expr SEMICOLON
-FnProto <- KEYWORD_fn IDENTIFIER? LPAREN ParamDeclList RPAREN ByteAlign? LinkSection? EXCLAMATIONMARK? (KEYWORD_var / TypeExpr)
+FnProto <- KEYWORD_fn IDENTIFIER? LPAREN ParamDeclList RPAREN ByteAlign? LinkSection? EXCLAMATIONMARK? (KEYWORD_anytype / TypeExpr)
VarDecl <- (KEYWORD_const / KEYWORD_var) IDENTIFIER (COLON TypeExpr)? ByteAlign? LinkSection? (EQUAL Expr)? SEMICOLON
@@ -10386,7 +10386,7 @@ LinkSection <- KEYWORD_linksection LPAREN Expr RPAREN
ParamDecl <- (KEYWORD_noalias / KEYWORD_comptime)? (IDENTIFIER COLON)? ParamType
ParamType
- <- KEYWORD_var
+ <- KEYWORD_anytype
/ DOT3
/ TypeExpr
@@ -10624,6 +10624,7 @@ KEYWORD_align <- 'align' end_of_word
KEYWORD_allowzero <- 'allowzero' end_of_word
KEYWORD_and <- 'and' end_of_word
KEYWORD_anyframe <- 'anyframe' end_of_word
+KEYWORD_anytype <- 'anytype' end_of_word
KEYWORD_asm <- 'asm' end_of_word
KEYWORD_async <- 'async' end_of_word
KEYWORD_await <- 'await' end_of_word
@@ -10669,14 +10670,14 @@ KEYWORD_var <- 'var' end_of_word
KEYWORD_volatile <- 'volatile' end_of_word
KEYWORD_while <- 'while' end_of_word
-keyword <- KEYWORD_align / KEYWORD_and / KEYWORD_allowzero / KEYWORD_asm
- / KEYWORD_async / KEYWORD_await / KEYWORD_break
+keyword <- KEYWORD_align / KEYWORD_and / KEYWORD_anyframe / KEYWORD_anytype
+ / KEYWORD_allowzero / KEYWORD_asm / KEYWORD_async / KEYWORD_await / KEYWORD_break
/ KEYWORD_catch / KEYWORD_comptime / KEYWORD_const / KEYWORD_continue
/ KEYWORD_defer / KEYWORD_else / KEYWORD_enum / KEYWORD_errdefer
/ KEYWORD_error / KEYWORD_export / KEYWORD_extern / KEYWORD_false
/ KEYWORD_fn / KEYWORD_for / KEYWORD_if / KEYWORD_inline
/ KEYWORD_noalias / KEYWORD_null / KEYWORD_or
- / KEYWORD_orelse / KEYWORD_packed / KEYWORD_anyframe / KEYWORD_pub
+ / KEYWORD_orelse / KEYWORD_packed / KEYWORD_pub
/ KEYWORD_resume / KEYWORD_return / KEYWORD_linksection
/ KEYWORD_struct / KEYWORD_suspend
/ KEYWORD_switch / KEYWORD_test / KEYWORD_threadlocal / KEYWORD_true / KEYWORD_try
diff --git a/src/all_types.hpp b/src/all_types.hpp
index 4465bf674c..a73efe2c82 100644
--- a/src/all_types.hpp
+++ b/src/all_types.hpp
@@ -692,7 +692,7 @@ enum NodeType {
NodeTypeSuspend,
NodeTypeAnyFrameType,
NodeTypeEnumLiteral,
- NodeTypeVarFieldType,
+ NodeTypeAnyTypeField,
};
enum FnInline {
@@ -705,7 +705,7 @@ struct AstNodeFnProto {
Buf *name;
ZigList");
var tokenizer = std.zig.Tokenizer.init(src);
@@ -825,6 +825,7 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
.Keyword_volatile,
.Keyword_allowzero,
.Keyword_while,
+ .Keyword_anytype,
=> {
try out.writeAll("");
try writeEscaped(out, src[token.loc.start..token.loc.end]);
@@ -977,12 +978,12 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
try out.writeAll("");
}
-fn tokenizeAndPrint(docgen_tokenizer: *Tokenizer, out: var, source_token: Token) !void {
+fn tokenizeAndPrint(docgen_tokenizer: *Tokenizer, out: anytype, source_token: Token) !void {
const raw_src = docgen_tokenizer.buffer[source_token.start..source_token.end];
return tokenizeAndPrintRaw(docgen_tokenizer, out, source_token, raw_src);
}
-fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var, zig_exe: []const u8) !void {
+fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: anytype, zig_exe: []const u8) !void {
var code_progress_index: usize = 0;
var env_map = try process.getEnvMap(allocator);
diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig
index 7415b1b520..7e288170af 100644
--- a/lib/std/fmt.zig
+++ b/lib/std/fmt.zig
@@ -69,7 +69,7 @@ fn peekIsAlign(comptime fmt: []const u8) bool {
///
/// If a formatted user type contains a function of the type
/// ```
-/// pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: var) !void
+/// pub fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void
/// ```
/// with `?` being the type formatted, this function will be called instead of the default implementation.
/// This allows user types to be formatted in a logical manner instead of dumping all fields of the type.
diff --git a/lib/std/io/serialization.zig b/lib/std/io/serialization.zig
index 8fe0782c84..317dde6417 100644
--- a/lib/std/io/serialization.zig
+++ b/lib/std/io/serialization.zig
@@ -16,14 +16,16 @@ pub const Packing = enum {
};
/// Creates a deserializer that deserializes types from any stream.
-/// If `is_packed` is true, the data stream is treated as bit-packed,
-/// otherwise data is expected to be packed to the smallest byte.
-/// Types may implement a custom deserialization routine with a
-/// function named `deserialize` in the form of:
-/// pub fn deserialize(self: *Self, deserializer: var) !void
-/// which will be called when the deserializer is used to deserialize
-/// that type. It will pass a pointer to the type instance to deserialize
-/// into and a pointer to the deserializer struct.
+/// If `is_packed` is true, the data stream is treated as bit-packed,
+/// otherwise data is expected to be packed to the smallest byte.
+/// Types may implement a custom deserialization routine with a
+/// function named `deserialize` in the form of:
+/// ```
+/// pub fn deserialize(self: *Self, deserializer: anytype) !void
+/// ```
+/// which will be called when the deserializer is used to deserialize
+/// that type. It will pass a pointer to the type instance to deserialize
+/// into and a pointer to the deserializer struct.
pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime ReaderType: type) type {
return struct {
in_stream: if (packing == .Bit) io.BitReader(endian, ReaderType) else ReaderType,
@@ -108,7 +110,7 @@ pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing,
const C = comptime meta.Child(T);
const child_type_id = @typeInfo(C);
- //custom deserializer: fn(self: *Self, deserializer: var) !void
+ //custom deserializer: fn(self: *Self, deserializer: anytype) !void
if (comptime trait.hasFn("deserialize")(C)) return C.deserialize(ptr, self);
if (comptime trait.isPacked(C) and packing != .Bit) {
@@ -196,18 +198,20 @@ pub fn deserializer(
}
/// Creates a serializer that serializes types to any stream.
-/// If `is_packed` is true, the data will be bit-packed into the stream.
-/// Note that the you must call `serializer.flush()` when you are done
-/// writing bit-packed data in order ensure any unwritten bits are committed.
-/// If `is_packed` is false, data is packed to the smallest byte. In the case
-/// of packed structs, the struct will written bit-packed and with the specified
-/// endianess, after which data will resume being written at the next byte boundary.
-/// Types may implement a custom serialization routine with a
-/// function named `serialize` in the form of:
-/// pub fn serialize(self: Self, serializer: var) !void
-/// which will be called when the serializer is used to serialize that type. It will
-/// pass a const pointer to the type instance to be serialized and a pointer
-/// to the serializer struct.
+/// If `is_packed` is true, the data will be bit-packed into the stream.
+/// Note that the you must call `serializer.flush()` when you are done
+/// writing bit-packed data in order ensure any unwritten bits are committed.
+/// If `is_packed` is false, data is packed to the smallest byte. In the case
+/// of packed structs, the struct will written bit-packed and with the specified
+/// endianess, after which data will resume being written at the next byte boundary.
+/// Types may implement a custom serialization routine with a
+/// function named `serialize` in the form of:
+/// ```
+/// pub fn serialize(self: Self, serializer: anytype) !void
+/// ```
+/// which will be called when the serializer is used to serialize that type. It will
+/// pass a const pointer to the type instance to be serialized and a pointer
+/// to the serializer struct.
pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime OutStreamType: type) type {
return struct {
out_stream: if (packing == .Bit) io.BitOutStream(endian, OutStreamType) else OutStreamType,
@@ -270,7 +274,7 @@ pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, co
return;
}
- //custom serializer: fn(self: Self, serializer: var) !void
+ //custom serializer: fn(self: Self, serializer: anytype) !void
if (comptime trait.hasFn("serialize")(T)) return T.serialize(value, self);
if (comptime trait.isPacked(T) and packing != .Bit) {
diff --git a/lib/std/log.zig b/lib/std/log.zig
index 0006580031..3fb75b7e37 100644
--- a/lib/std/log.zig
+++ b/lib/std/log.zig
@@ -22,7 +22,7 @@ const root = @import("root");
//! comptime level: std.log.Level,
//! comptime scope: @TypeOf(.EnumLiteral),
//! comptime format: []const u8,
-//! args: var,
+//! args: anytype,
//! ) void {
//! // Ignore all non-critical logging from sources other than
//! // .my_project and .nice_library
diff --git a/lib/std/zig/ast.zig b/lib/std/zig/ast.zig
index 7cb4936444..0502f5bb64 100644
--- a/lib/std/zig/ast.zig
+++ b/lib/std/zig/ast.zig
@@ -1052,12 +1052,12 @@ pub const Node = struct {
const params_len: usize = if (self.params_len == 0)
0
else switch (self.paramsConst()[self.params_len - 1].param_type) {
- .var_type, .type_expr => self.params_len,
+ .any_type, .type_expr => self.params_len,
.var_args => self.params_len - 1,
};
if (i < params_len) {
switch (self.paramsConst()[i].param_type) {
- .var_type => |n| return n,
+ .any_type => |n| return n,
.var_args => unreachable,
.type_expr => |n| return n,
}
diff --git a/src-self-hosted/Module.zig b/src-self-hosted/Module.zig
index b0678ea665..d173bd36e8 100644
--- a/src-self-hosted/Module.zig
+++ b/src-self-hosted/Module.zig
@@ -1132,7 +1132,7 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
const param_types = try fn_type_scope.arena.alloc(*zir.Inst, param_decls.len);
for (param_decls) |param_decl, i| {
const param_type_node = switch (param_decl.param_type) {
- .var_type => |node| return self.failNode(&fn_type_scope.base, node, "TODO implement anytype parameter", .{}),
+ .any_type => |node| return self.failNode(&fn_type_scope.base, node, "TODO implement anytype parameter", .{}),
.var_args => |tok| return self.failTok(&fn_type_scope.base, tok, "TODO implement var args", .{}),
.type_expr => |node| node,
};
diff --git a/src/analyze.cpp b/src/analyze.cpp
index 5eba515e68..67c900507d 100644
--- a/src/analyze.cpp
+++ b/src/analyze.cpp
@@ -1511,13 +1511,13 @@ ZigType *get_generic_fn_type(CodeGen *g, FnTypeId *fn_type_id) {
}
for (; i < fn_type_id->param_count; i += 1) {
const char *comma_str = (i == 0) ? "" : ",";
- buf_appendf(&fn_type->name, "%svar", comma_str);
+ buf_appendf(&fn_type->name, "%sanytype", comma_str);
}
buf_append_str(&fn_type->name, ")");
if (fn_type_id->cc != CallingConventionUnspecified) {
buf_appendf(&fn_type->name, " callconv(.%s)", calling_convention_name(fn_type_id->cc));
}
- buf_append_str(&fn_type->name, " var");
+ buf_append_str(&fn_type->name, " anytype");
fn_type->data.fn.fn_type_id = *fn_type_id;
fn_type->data.fn.is_generic = true;
diff --git a/test/compile_errors.zig b/test/compile_errors.zig
index df2e759bf1..fb4428fbc6 100644
--- a/test/compile_errors.zig
+++ b/test/compile_errors.zig
@@ -42,7 +42,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
\\fn foo() Foo {
\\ return .{ .x = 42 };
\\}
- \\fn bar(val: var) Foo {
+ \\fn bar(val: anytype) Foo {
\\ return .{ .x = val };
\\}
\\export fn entry() void {
@@ -1034,7 +1034,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
\\ storev(&v[i], 42);
\\}
\\
- \\fn storev(ptr: var, val: i32) void {
+ \\fn storev(ptr: anytype, val: i32) void {
\\ ptr.* = val;
\\}
, &[_][]const u8{
@@ -1049,7 +1049,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
\\ var x = loadv(&v[i]);
\\}
\\
- \\fn loadv(ptr: var) i32 {
+ \\fn loadv(ptr: anytype) i32 {
\\ return ptr.*;
\\}
, &[_][]const u8{
@@ -1832,7 +1832,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
\\ while (true) {}
\\}
, &[_][]const u8{
- "error: expected type 'fn([]const u8, ?*std.builtin.StackTrace) noreturn', found 'fn([]const u8,var) var'",
+ "error: expected type 'fn([]const u8, ?*std.builtin.StackTrace) noreturn', found 'fn([]const u8,anytype) anytype'",
"note: only one of the functions is generic",
});
@@ -2032,11 +2032,11 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
});
cases.add("export generic function",
- \\export fn foo(num: var) i32 {
+ \\export fn foo(num: anytype) i32 {
\\ return 0;
\\}
, &[_][]const u8{
- "tmp.zig:1:15: error: parameter of type 'var' not allowed in function with calling convention 'C'",
+ "tmp.zig:1:15: error: parameter of type 'anytype' not allowed in function with calling convention 'C'",
});
cases.add("C pointer to c_void",
@@ -2836,7 +2836,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
});
cases.add("missing parameter name of generic function",
- \\fn dump(var) void {}
+ \\fn dump(anytype) void {}
\\export fn entry() void {
\\ var a: u8 = 9;
\\ dump(a);
@@ -2859,13 +2859,13 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
});
cases.add("generic fn as parameter without comptime keyword",
- \\fn f(_: fn (var) void) void {}
- \\fn g(_: var) void {}
+ \\fn f(_: fn (anytype) void) void {}
+ \\fn g(_: anytype) void {}
\\export fn entry() void {
\\ f(g);
\\}
, &[_][]const u8{
- "tmp.zig:1:9: error: parameter of type 'fn(var) var' must be declared comptime",
+ "tmp.zig:1:9: error: parameter of type 'fn(anytype) anytype' must be declared comptime",
});
cases.add("optional pointer to void in extern struct",
@@ -3165,7 +3165,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
cases.add("var makes structs required to be comptime known",
\\export fn entry() void {
- \\ const S = struct{v: var};
+ \\ const S = struct{v: anytype};
\\ var s = S{.v=@as(i32, 10)};
\\}
, &[_][]const u8{
@@ -6072,10 +6072,10 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
});
cases.add("calling a generic function only known at runtime",
- \\var foos = [_]fn(var) void { foo1, foo2 };
+ \\var foos = [_]fn(anytype) void { foo1, foo2 };
\\
- \\fn foo1(arg: var) void {}
- \\fn foo2(arg: var) void {}
+ \\fn foo1(arg: anytype) void {}
+ \\fn foo2(arg: anytype) void {}
\\
\\pub fn main() !void {
\\ foos[0](true);
@@ -6920,12 +6920,12 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
});
cases.add("getting return type of generic function",
- \\fn generic(a: var) void {}
+ \\fn generic(a: anytype) void {}
\\comptime {
\\ _ = @TypeOf(generic).ReturnType;
\\}
, &[_][]const u8{
- "tmp.zig:3:25: error: ReturnType has not been resolved because 'fn(var) var' is generic",
+ "tmp.zig:3:25: error: ReturnType has not been resolved because 'fn(anytype) anytype' is generic",
});
cases.add("unsupported modifier at start of asm output constraint",
@@ -7493,7 +7493,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
});
cases.add("issue #5221: invalid struct init type referenced by @typeInfo and passed into function",
- \\fn ignore(comptime param: var) void {}
+ \\fn ignore(comptime param: anytype) void {}
\\
\\export fn foo() void {
\\ const MyStruct = struct {
From f23987db7d83403fc504b63171531e9ad1ffdc1a Mon Sep 17 00:00:00 2001
From: Andrew Kelley
User documentation that doesn't belong to whatever + immediately follows it, like package-level documentation, goes + in top-level doc comments. A top-level doc comment is one that + begins with two slashes and an exclamation point: + {#syntax#}//!{#endsyntax#}.
+ {#code_begin|syntax|tldoc_comments#} +//! This module provides functions for retrieving the current date and +//! time with varying degrees of precision and accuracy. It does not +//! depend on libc, but will use functions from it if available. + {#code_end#} + {#header_close#} {#header_close#} {#header_open|Values#} {#code_begin|exe|values#} From 14cef9dd3d8074b0dc2ee48a0905300ce6317aed Mon Sep 17 00:00:00 2001 From: Andrew Kelley- A vector is a group of {#link|Integers#}, {#link|Floats#}, or {#link|Pointers#} which are operated on + A vector is a group of booleans, {#link|Integers#}, {#link|Floats#}, or {#link|Pointers#} which are operated on in parallel using a single instruction ({#link|SIMD#}). Vector types are created with the builtin function {#link|@Type#}, or using the shorthand as {#syntax#}std.meta.Vector{#endsyntax#}.
From 06c08e5219f03328f483cded319c7ba75efb5188 Mon Sep 17 00:00:00 2001 From: Vexu