Generate data files in config_gen.zig (#903)

* generate data files in config_gen.zig

* remove trailing comma from config.json

* update README.md

* run zig build gen

* handle some unclosed tags

* update data file header

* generate new data files

* remove old data file generators
This commit is contained in:
Techatrix 2023-01-19 07:46:42 +01:00 committed by GitHub
parent 6949989ece
commit fa5828496e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 4508 additions and 2656 deletions

View File

@ -44,17 +44,8 @@ zig build -Drelease-safe
#### Updating Data Files
There is a `generate-data.py` in the `src/data` folder, run this file to update data files.
It writes to stdout and you can redirect output to a zig file like `master.zig`. By default it generates data file for `master`, but can be configured to generate for a different version by modifying the `zig_version` variable. Files generated by this tool **contains** formatting information.
On Powershell 5.1 (the default Powershell on Windows 10 & 11), the following will update `master.zig`.
```pwsh
New-Item -Force .\src\data\master.zig -Value ((python .\src\data\generate-data.py) -split "`r?`n" -join "`n")
```
This unweidly command is necesary in order to guarantee Unix-style line endings and UTF-8 text encoding.
There is also a `generate-data.js` in the `src/data` folder, you'll need to run this inside a Chrome DevTools console and copy the output. Files generated by this tool **does not contain** formatting information.
Run `zig build gen -- --generate-version-data master` to update data files. This command will require an internet connection.
You can replace `master` with a specific zig version like `0.10.0`. Which version ZLS uses can be configured by passing the `-Ddata_version` parameter when building ZLS.
### Configuration Options

View File

@ -146,14 +146,12 @@ pub fn build(b: *std.build.Builder) !void {
const gen_cmd = gen_exe.run();
gen_cmd.addArgs(&.{
b.fmt("{s}/src/Config.zig", .{b.build_root}),
b.fmt("{s}/schema.json", .{b.build_root}),
b.fmt("{s}/README.md", .{b.build_root}),
b.pathJoin(&.{ b.build_root, "src", "Config.zig" }),
b.pathJoin(&.{ b.build_root, "schema.json" }),
b.pathJoin(&.{ b.build_root, "README.md" }),
b.pathJoin(&.{ b.build_root, "src", "data" }),
});
if (b.option([]const u8, "vscode-config-path", "Output path to vscode-config")) |path| {
gen_cmd.addArg(b.pathFromRoot(path));
}
if (b.args) |args| gen_cmd.addArgs(args);
const gen_step = b.step("gen", "Regenerate config files");
gen_step.dependOn(&check_submodules_step.step);

View File

@ -1,7 +1,7 @@
//! DO NOT EDIT
//! Configuration options for zls.
//! If you want to add a config option edit
//! src/config_gen/config.zig and run `zig build gen`
//! src/config_gen/config.json and run `zig build gen`
//! GENERATED BY src/config_gen/config_gen.zig
/// Enables snippet completions when the client also supports them

View File

@ -4,7 +4,7 @@
"name": "enable_snippets",
"description": "Enables snippet completions when the client also supports them",
"type": "bool",
"default": "true",
"default": "true"
},
{
"name": "enable_ast_check_diagnostics",
@ -16,13 +16,13 @@
"name": "enable_autofix",
"description": "Whether to automatically fix errors on save. Currently supports adding and removing discards.",
"type": "bool",
"default": "true",
"default": "true"
},
{
"name": "enable_import_embedfile_argument_completions",
"description": "Whether to enable import/embedFile argument completions",
"type": "bool",
"default": "true",
"default": "true"
},
{
"name": "enable_semantic_tokens",
@ -34,7 +34,7 @@
"name": "enable_inlay_hints",
"description": "Enables inlay hint support when the client also supports it",
"type": "bool",
"default": "true",
"default": "true"
},
{
"name": "inlay_hints_show_builtin",

View File

@ -1,5 +1,6 @@
const std = @import("std");
const builtin = @import("builtin");
const zig_builtin = @import("builtin");
const tres = @import("tres");
const ConfigOption = struct {
@ -54,7 +55,7 @@ fn generateConfigFile(allocator: std.mem.Allocator, config: Config, path: []cons
\\//! DO NOT EDIT
\\//! Configuration options for zls.
\\//! If you want to add a config option edit
\\//! src/config_gen/config.zig and run `zig build gen`
\\//! src/config_gen/config.json and run `zig build gen`
\\//! GENERATED BY src/config_gen/config_gen.zig
\\
);
@ -229,18 +230,728 @@ fn generateVSCodeConfigFile(allocator: std.mem.Allocator, config: Config, path:
try buffered_writer.flush();
}
/// Tokenizer for a langref.html.in file
/// example file: https://raw.githubusercontent.com/ziglang/zig/master/doc/langref.html.in
/// this is a modified version from https://github.com/ziglang/zig/blob/master/doc/docgen.zig
const Tokenizer = struct {
buffer: []const u8,
index: usize = 0,
state: State = .Start,
const State = enum {
Start,
LBracket,
Hash,
TagName,
Eof,
};
const Token = struct {
id: Id,
start: usize,
end: usize,
const Id = enum {
Invalid,
Content,
BracketOpen,
TagContent,
Separator,
BracketClose,
Eof,
};
};
fn next(self: *Tokenizer) Token {
var result = Token{
.id = .Eof,
.start = self.index,
.end = undefined,
};
while (self.index < self.buffer.len) : (self.index += 1) {
const c = self.buffer[self.index];
switch (self.state) {
.Start => switch (c) {
'{' => {
self.state = .LBracket;
},
else => {
result.id = .Content;
},
},
.LBracket => switch (c) {
'#' => {
if (result.id != .Eof) {
self.index -= 1;
self.state = .Start;
break;
} else {
result.id = .BracketOpen;
self.index += 1;
self.state = .TagName;
break;
}
},
else => {
result.id = .Content;
self.state = .Start;
},
},
.TagName => switch (c) {
'|' => {
if (result.id != .Eof) {
break;
} else {
result.id = .Separator;
self.index += 1;
break;
}
},
'#' => {
self.state = .Hash;
},
else => {
result.id = .TagContent;
},
},
.Hash => switch (c) {
'}' => {
if (result.id != .Eof) {
self.index -= 1;
self.state = .TagName;
break;
} else {
result.id = .BracketClose;
self.index += 1;
self.state = .Start;
break;
}
},
else => {
result.id = .TagContent;
self.state = .TagName;
},
},
.Eof => unreachable,
}
} else {
switch (self.state) {
.Start,
.LBracket,
.Eof,
=> {},
else => {
result.id = .Invalid;
},
}
self.state = .Eof;
}
result.end = self.index;
return result;
}
};
const Builtin = struct {
name: []const u8,
signature: []const u8,
documentation: std.ArrayListUnmanaged(u8),
};
/// parses a `langref.html.in` file and extracts builtins from this section: `https://ziglang.org/documentation/master/#Builtin-Functions`
/// the documentation field contains poorly formated html
fn collectBuiltinData(allocator: std.mem.Allocator, version: []const u8, langref_file: []const u8) error{OutOfMemory}![]Builtin {
var tokenizer = Tokenizer{ .buffer = langref_file };
const State = enum {
/// searching for this line:
/// {#header_open|Builtin Functions|2col#}
searching,
/// skippig builtin functions description:
/// Builtin functions are provided by the compiler and are prefixed ...
prefix,
/// every entry begins with this:
/// {#syntax#}@addrSpaceCast(comptime addrspace: std.builtin.AddressSpace, ptr: anytype) anytype{#endsyntax#}
builtin_begin,
/// iterate over documentation
builtin_content,
};
var state: State = .searching;
var builtins = std.ArrayListUnmanaged(Builtin){};
errdefer {
for (builtins.items) |*builtin| {
builtin.documentation.deinit(allocator);
}
builtins.deinit(allocator);
}
var depth: u32 = undefined;
while (true) {
const token = tokenizer.next();
switch (token.id) {
.Content => {
switch (state) {
.builtin_content => {
try builtins.items[builtins.items.len - 1].documentation.appendSlice(allocator, tokenizer.buffer[token.start..token.end]);
},
else => continue,
}
},
.BracketOpen => {
const tag_token = tokenizer.next();
std.debug.assert(tag_token.id == .TagContent);
const tag_name = tokenizer.buffer[tag_token.start..tag_token.end];
if (std.mem.eql(u8, tag_name, "header_open")) {
std.debug.assert(tokenizer.next().id == .Separator);
const content_token = tokenizer.next();
std.debug.assert(tag_token.id == .TagContent);
const content_name = tokenizer.buffer[content_token.start..content_token.end];
switch (state) {
.searching => {
if (std.mem.eql(u8, content_name, "Builtin Functions")) {
state = .prefix;
depth = 0;
}
},
.prefix, .builtin_begin => {
state = .builtin_begin;
try builtins.append(allocator, .{
.name = content_name,
.signature = "",
.documentation = .{},
});
},
.builtin_content => unreachable,
}
if (state != .searching) {
depth += 1;
}
while (true) {
const bracket_tok = tokenizer.next();
switch (bracket_tok.id) {
.BracketClose => break,
.Separator, .TagContent => continue,
else => unreachable,
}
}
} else if (std.mem.eql(u8, tag_name, "header_close")) {
std.debug.assert(tokenizer.next().id == .BracketClose);
if (state == .builtin_content) {
state = .builtin_begin;
}
if (state != .searching) {
depth -= 1;
if (depth == 0) break;
}
} else if (state != .searching and std.mem.eql(u8, tag_name, "syntax")) {
std.debug.assert(tokenizer.next().id == .BracketClose);
const content_tag = tokenizer.next();
std.debug.assert(content_tag.id == .Content);
const content_name = tokenizer.buffer[content_tag.start..content_tag.end];
std.debug.assert(tokenizer.next().id == .BracketOpen);
const end_syntax_tag = tokenizer.next();
std.debug.assert(end_syntax_tag.id == .TagContent);
const end_tag_name = tokenizer.buffer[end_syntax_tag.start..end_syntax_tag.end];
std.debug.assert(std.mem.eql(u8, end_tag_name, "endsyntax"));
std.debug.assert(tokenizer.next().id == .BracketClose);
switch (state) {
.builtin_begin => {
builtins.items[builtins.items.len - 1].signature = content_name;
state = .builtin_content;
},
.builtin_content => {
const writer = builtins.items[builtins.items.len - 1].documentation.writer(allocator);
try writeMarkdownCode(content_name, "zig", writer);
},
else => {},
}
} else if (state != .searching and std.mem.eql(u8, tag_name, "syntax_block")) {
std.debug.assert(tokenizer.next().id == .Separator);
const source_type_tag = tokenizer.next();
std.debug.assert(tag_token.id == .TagContent);
const source_type = tokenizer.buffer[source_type_tag.start..source_type_tag.end];
switch (tokenizer.next().id) {
.Separator => {
std.debug.assert(tokenizer.next().id == .TagContent);
std.debug.assert(tokenizer.next().id == .BracketClose);
},
.BracketClose => {},
else => unreachable,
}
var content_token = tokenizer.next();
std.debug.assert(content_token.id == .Content);
const content = tokenizer.buffer[content_token.start..content_token.end];
const writer = builtins.items[builtins.items.len - 1].documentation.writer(allocator);
try writeMarkdownCode(content, source_type, writer);
std.debug.assert(tokenizer.next().id == .BracketOpen);
const end_code_token = tokenizer.next();
std.debug.assert(tag_token.id == .TagContent);
const end_code_name = tokenizer.buffer[end_code_token.start..end_code_token.end];
std.debug.assert(std.mem.eql(u8, end_code_name, "end_syntax_block"));
std.debug.assert(tokenizer.next().id == .BracketClose);
} else if (state != .searching and std.mem.eql(u8, tag_name, "link")) {
std.debug.assert(tokenizer.next().id == .Separator);
const name_token = tokenizer.next();
std.debug.assert(name_token.id == .TagContent);
const name = tokenizer.buffer[name_token.start..name_token.end];
const url_name = switch (tokenizer.next().id) {
.Separator => blk: {
const url_name_token = tokenizer.next();
std.debug.assert(url_name_token.id == .TagContent);
const url_name = tokenizer.buffer[url_name_token.start..url_name_token.end];
std.debug.assert(tokenizer.next().id == .BracketClose);
break :blk url_name;
},
.BracketClose => name,
else => unreachable,
};
const spaceless_url_name = try std.mem.replaceOwned(u8, allocator, url_name, " ", "-");
defer allocator.free(spaceless_url_name);
const writer = builtins.items[builtins.items.len - 1].documentation.writer(allocator);
try writer.print("[{s}](https://ziglang.org/documentation/{s}/#{s})", .{
name,
version,
std.mem.trimLeft(u8, spaceless_url_name, "@"),
});
} else if (state != .searching and std.mem.eql(u8, tag_name, "code_begin")) {
std.debug.assert(tokenizer.next().id == .Separator);
std.debug.assert(tokenizer.next().id == .TagContent);
switch (tokenizer.next().id) {
.Separator => {
std.debug.assert(tokenizer.next().id == .TagContent);
std.debug.assert(tokenizer.next().id == .BracketClose);
},
.BracketClose => {},
else => unreachable,
}
while (true) {
const content_token = tokenizer.next();
std.debug.assert(content_token.id == .Content);
const content = tokenizer.buffer[content_token.start..content_token.end];
std.debug.assert(tokenizer.next().id == .BracketOpen);
const end_code_token = tokenizer.next();
std.debug.assert(end_code_token.id == .TagContent);
const end_tag_name = tokenizer.buffer[end_code_token.start..end_code_token.end];
if (std.mem.eql(u8, end_tag_name, "code_end")) {
std.debug.assert(tokenizer.next().id == .BracketClose);
const writer = builtins.items[builtins.items.len - 1].documentation.writer(allocator);
try writeMarkdownCode(content, "zig", writer);
break;
}
std.debug.assert(tokenizer.next().id == .BracketClose);
}
} else {
while (true) {
switch (tokenizer.next().id) {
.Eof => unreachable,
.BracketClose => break,
else => continue,
}
}
}
},
else => unreachable,
}
}
return try builtins.toOwnedSlice(allocator);
}
/// single line: \`{content}\`
/// multi line:
/// \`\`\`{source_type}
/// {content}
/// \`\`\`
fn writeMarkdownCode(content: []const u8, source_type: []const u8, writer: anytype) @TypeOf(writer).Error!void {
const trimmed_content = std.mem.trim(u8, content, " \n");
const is_multiline = std.mem.indexOfScalar(u8, trimmed_content, '\n') != null;
if (is_multiline) {
var line_it = std.mem.tokenize(u8, trimmed_content, "\n");
try writer.print("\n```{s}", .{source_type});
while (line_it.next()) |line| {
try writer.print("\n{s}", .{line});
}
try writer.writeAll("\n```");
} else {
try writer.print("`{s}`", .{trimmed_content});
}
}
fn writeLine(str: []const u8, single_line: bool, writer: anytype) @TypeOf(writer).Error!void {
const trimmed_content = std.mem.trim(u8, str, &std.ascii.whitespace);
if (trimmed_content.len == 0) return;
if (single_line) {
var line_it = std.mem.split(u8, trimmed_content, "\n");
while (line_it.next()) |line| {
try writer.print("{s} ", .{std.mem.trim(u8, line, &std.ascii.whitespace)});
}
} else {
try writer.writeAll(trimmed_content);
}
try writer.writeByte('\n');
}
/// converts text with various html tags into markdown
/// supported tags:
/// - `<p>`
/// - `<pre>`
/// - `<em>`
/// - `<ul>` and `<li>`
/// - `<a>`
/// - `<code>`
fn writeMarkdownFromHtml(html: []const u8, writer: anytype) !void {
return writeMarkdownFromHtmlInternal(html, false, 0, writer);
}
/// this is kind of a hacky solution. A cleaner solution would be to implement using a xml/html parser.
fn writeMarkdownFromHtmlInternal(html: []const u8, single_line: bool, depth: u32, writer: anytype) !void {
var index: usize = 0;
while (std.mem.indexOfScalarPos(u8, html, index, '<')) |tag_start_index| {
const tags: []const []const u8 = &.{ "pre", "p", "em", "ul", "li", "a", "code" };
const opening_tags: []const []const u8 = &.{ "<pre>", "<p>", "<em>", "<ul>", "<li>", "<a>", "<code>" };
const closing_tags: []const []const u8 = &.{ "</pre>", "</p>", "</em>", "</ul>", "</li>", "</a>", "</code>" };
const tag_index = for (tags) |tag_name, i| {
if (std.mem.startsWith(u8, html[tag_start_index + 1 ..], tag_name)) break i;
} else {
index += 1;
continue;
};
try writeLine(html[index..tag_start_index], single_line, writer);
const tag_name = tags[tag_index];
const opening_tag_name = opening_tags[tag_index];
const closing_tag_name = closing_tags[tag_index];
// std.debug.print("tag: '{s}'\n", .{tag_name});
const content_start = 1 + (std.mem.indexOfScalarPos(u8, html, tag_start_index + 1 + tag_name.len, '>') orelse return error.InvalidTag);
index = content_start;
const content_end = while (std.mem.indexOfScalarPos(u8, html, index, '<')) |end| {
if (std.mem.startsWith(u8, html[end..], closing_tag_name)) break end;
if (std.mem.startsWith(u8, html[end..], opening_tag_name)) {
index = std.mem.indexOfPos(u8, html, end + opening_tag_name.len, closing_tag_name) orelse return error.MissingEndTag;
index += closing_tag_name.len;
continue;
}
index += 1;
} else html.len;
const content = html[content_start..content_end];
index = @min(html.len, content_end + closing_tag_name.len);
// std.debug.print("content: {s}\n", .{content});
if (std.mem.eql(u8, tag_name, "p")) {
try writeMarkdownFromHtmlInternal(content, true, depth, writer);
try writer.writeByte('\n');
} else if (std.mem.eql(u8, tag_name, "pre")) {
try writeMarkdownFromHtmlInternal(content, false, depth, writer);
} else if (std.mem.eql(u8, tag_name, "em")) {
try writer.print("**{s}** ", .{content});
} else if (std.mem.eql(u8, tag_name, "ul")) {
try writeMarkdownFromHtmlInternal(content, false, depth + 1, writer);
} else if (std.mem.eql(u8, tag_name, "li")) {
try writer.writeByteNTimes(' ', 1 + (depth -| 1) * 2);
try writer.writeAll("- ");
try writeMarkdownFromHtmlInternal(content, true, depth, writer);
} else if (std.mem.eql(u8, tag_name, "a")) {
const href_part = std.mem.trimLeft(u8, html[tag_start_index + 2 .. content_start - 1], " ");
std.debug.assert(std.mem.startsWith(u8, href_part, "href=\""));
std.debug.assert(href_part[href_part.len - 1] == '\"');
const url = href_part["href=\"".len .. href_part.len - 1];
try writer.print("[{s}]({s})", .{ content, std.mem.trimLeft(u8, url, "@") });
} else if (std.mem.eql(u8, tag_name, "code")) {
try writeMarkdownCode(content, "zig", writer);
} else return error.UnsupportedTag;
}
try writeLine(html[index..], single_line, writer);
}
/// takes in a signature like this: `@intToEnum(comptime DestType: type, integer: anytype) DestType`
/// and outputs its arguments: `comptime DestType: type`, `integer: anytype`
fn extractArgumentsFromSignature(allocator: std.mem.Allocator, signature: []const u8) error{OutOfMemory}![][]const u8 {
var arguments = std.ArrayListUnmanaged([]const u8){};
defer arguments.deinit(allocator);
var argument_start: usize = 0;
var index: usize = 0;
while (std.mem.indexOfAnyPos(u8, signature, index, ",()")) |token_index| {
if (signature[token_index] == '(') {
argument_start = index;
index = 1 + std.mem.indexOfScalarPos(u8, signature, token_index + 1, ')').?;
continue;
}
const argument = std.mem.trim(u8, signature[argument_start..token_index], &std.ascii.whitespace);
if (argument.len != 0) try arguments.append(allocator, argument);
if (signature[token_index] == ')') break;
argument_start = token_index + 1;
index = token_index + 1;
}
return arguments.toOwnedSlice(allocator);
}
/// takes in a signature like this: `@intToEnum(comptime DestType: type, integer: anytype) DestType`
/// and outputs a snippet: `@intToEnum(${1:comptime DestType: type}, ${2:integer: anytype})`
fn extractSnippetFromSignature(allocator: std.mem.Allocator, signature: []const u8) error{OutOfMemory}![]const u8 {
var snippet = std.ArrayListUnmanaged(u8){};
defer snippet.deinit(allocator);
var writer = snippet.writer(allocator);
const start_index = 1 + std.mem.indexOfScalar(u8, signature, '(').?;
try writer.writeAll(signature[0..start_index]);
var argument_start: usize = start_index;
var index: usize = start_index;
var i: u32 = 1;
while (std.mem.indexOfAnyPos(u8, signature, index, ",()")) |token_index| {
if (signature[token_index] == '(') {
argument_start = index;
index = 1 + std.mem.indexOfScalarPos(u8, signature, token_index + 1, ')').?;
continue;
}
const argument = std.mem.trim(u8, signature[argument_start..token_index], &std.ascii.whitespace);
if (argument.len != 0) {
if (i != 1) try writer.writeAll(", ");
try writer.print("${{{d}:{s}}}", .{ i, argument });
}
if (signature[token_index] == ')') break;
argument_start = token_index + 1;
index = token_index + 1;
i += 1;
}
try writer.writeByte(')');
return snippet.toOwnedSlice(allocator);
}
/// Generates data files from the Zig language Reference (https://ziglang.org/documentation/master/)
/// An output example would `zls/src/master.zig`
fn generateVersionDataFile(allocator: std.mem.Allocator, version: []const u8, path: []const u8) !void {
const url = try std.fmt.allocPrint(allocator, "https://raw.githubusercontent.com/ziglang/zig/{s}/doc/langref.html.in", .{version});
defer allocator.free(url);
const response = try httpGET(allocator, try std.Uri.parse(url));
switch (response) {
.ok => {},
.other => |status| {
const error_name = status.phrase() orelse @tagName(status.class());
std.log.err("failed to download {s}: {s}", .{ url, error_name });
return error.DownloadFailed;
},
}
defer allocator.free(response.ok);
const response_bytes = response.ok;
// const response_bytes: []const u8 = @embedFile("langref.html.in");
var builtins = try collectBuiltinData(allocator, version, response_bytes);
defer {
for (builtins) |*builtin| {
builtin.documentation.deinit(allocator);
}
allocator.free(builtins);
}
var builtin_file = try std.fs.createFileAbsolute(path, .{});
defer builtin_file.close();
var buffered_writer = std.io.bufferedWriter(builtin_file.writer());
var writer = buffered_writer.writer();
try writer.print(
\\//! DO NOT EDIT
\\//! If you want to update this file run:
\\//! `zig build gen -- --generate-version-data {s}` (requires an internet connection)
\\//! GENERATED BY src/config_gen/config_gen.zig
\\
\\const Builtin = struct {{
\\ name: []const u8,
\\ signature: []const u8,
\\ snippet: []const u8,
\\ documentation: []const u8,
\\ arguments: []const []const u8,
\\}};
\\
\\pub const builtins = [_]Builtin{{
\\
, .{version});
for (builtins) |builtin| {
const signature = try std.mem.replaceOwned(u8, allocator, builtin.signature, "\n", "");
defer allocator.free(signature);
const snippet = try extractSnippetFromSignature(allocator, signature);
defer allocator.free(snippet);
var arguments = try extractArgumentsFromSignature(allocator, signature[builtin.name.len + 1 ..]);
defer allocator.free(arguments);
try writer.print(
\\ .{{
\\ .name = "{}",
\\ .signature = "{}",
\\ .snippet = "{}",
\\
, .{
std.zig.fmtEscapes(builtin.name),
std.zig.fmtEscapes(signature),
std.zig.fmtEscapes(snippet),
});
const html = builtin.documentation.items["</pre>".len..];
var markdown = std.ArrayListUnmanaged(u8){};
defer markdown.deinit(allocator);
try writeMarkdownFromHtml(html, markdown.writer(allocator));
try writer.writeAll(" .documentation =\n");
var line_it = std.mem.split(u8, std.mem.trim(u8, markdown.items, "\n"), "\n");
while (line_it.next()) |line| {
try writer.print(" \\\\{s}\n", .{std.mem.trimRight(u8, line, " ")});
}
try writer.writeAll(
\\ ,
\\ .arguments = &.{
);
if (arguments.len != 0) {
try writer.writeByte('\n');
for (arguments) |arg| {
try writer.print(" \"{}\",\n", .{std.zig.fmtEscapes(arg)});
}
try writer.writeByteNTimes(' ', 8);
}
try writer.writeAll(
\\},
\\ },
\\
);
}
try writer.writeAll(
\\};
\\
\\// DO NOT EDIT
\\
);
try buffered_writer.flush();
}
const Response = union(enum) {
ok: []const u8,
other: std.http.Status,
};
fn httpGET(allocator: std.mem.Allocator, uri: std.Uri) !Response {
var client = std.http.Client{ .allocator = allocator };
defer client.deinit(allocator);
try client.ca_bundle.rescan(allocator);
var request = try client.request(uri, .{}, .{});
defer request.deinit();
var output = std.ArrayListUnmanaged(u8){};
defer output.deinit(allocator);
var buffer: [1024]u8 = undefined;
while (true) {
const size = try request.read(&buffer);
if (size == 0) break;
try output.appendSlice(allocator, buffer[0..size]);
}
if (request.response.headers.status != .ok) {
return .{
.other = request.response.headers.status,
};
}
return .{ .ok = try output.toOwnedSlice(allocator) };
}
pub fn main() !void {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(!general_purpose_allocator.deinit());
var gpa = general_purpose_allocator.allocator();
var arg_it = try std.process.argsWithAllocator(gpa);
defer arg_it.deinit();
var stderr = std.io.getStdErr().writer();
_ = arg_it.next() orelse @panic("");
const config_path = arg_it.next() orelse @panic("first argument must be path to Config.zig");
const schema_path = arg_it.next() orelse @panic("second argument must be path to schema.json");
const readme_path = arg_it.next() orelse @panic("third argument must be path to README.md");
const maybe_vscode_config_path = arg_it.next();
var args_it = try std.process.argsWithAllocator(gpa);
defer args_it.deinit();
_ = args_it.next() orelse @panic("");
const config_path = args_it.next() orelse @panic("first argument must be path to Config.zig");
const schema_path = args_it.next() orelse @panic("second argument must be path to schema.json");
const readme_path = args_it.next() orelse @panic("third argument must be path to README.md");
const data_path = args_it.next() orelse @panic("fourth argument must be path to data directory");
var maybe_vscode_config_path: ?[]const u8 = null;
var maybe_data_file_version: ?[]const u8 = null;
var maybe_data_file_path: ?[]const u8 = null;
while (args_it.next()) |argname| {
if (std.mem.eql(u8, argname, "--help")) {
try stderr.writeAll(
\\ Usage: zig build gen -- [command]
\\
\\ Commands:
\\
\\ --help Prints this message
\\ --vscode-config-path [path] Output zls-vscode configurations
\\ --generate-version-data [version] Output version data file (see src/data/master.zig)
\\ --generate-version-data-path [path] Override default data file path (default: src/data/*.zig)
\\
);
} else if (std.mem.eql(u8, argname, "--vscode-config-path")) {
maybe_vscode_config_path = args_it.next() orelse {
try stderr.print("Expected output path after --vscode-config-path argument.\n", .{});
return;
};
} else if (std.mem.eql(u8, argname, "--generate-version-data")) {
maybe_data_file_version = args_it.next() orelse {
try stderr.print("Expected version after --generate-version-data argument.\n", .{});
return;
};
const is_valid_version = blk: {
if (std.mem.eql(u8, maybe_data_file_version.?, "master")) break :blk true;
_ = std.SemanticVersion.parse(maybe_data_file_version.?) catch break :blk false;
break :blk true;
};
if (!is_valid_version) {
try stderr.print("'{s}' is not a valid argument after --generate-version-data.\n", .{maybe_data_file_version.?});
return;
}
} else if (std.mem.eql(u8, argname, "--generate-version-data-path")) {
maybe_data_file_path = args_it.next() orelse {
try stderr.print("Expected output path after --generate-version-data-path argument.\n", .{});
return;
};
} else {
try stderr.print("Unrecognized argument '{s}'.\n", .{argname});
return;
}
}
const parse_options = std.json.ParseOptions{
.allocator = gpa,
@ -257,13 +968,22 @@ pub fn main() !void {
try generateVSCodeConfigFile(gpa, config, vscode_config_path);
}
if (builtin.os.tag == .windows) {
if (maybe_data_file_version) |data_version| {
const path = if (maybe_data_file_path) |path| path else blk: {
const file_name = try std.fmt.allocPrint(gpa, "{s}.zig", .{data_version});
defer gpa.free(file_name);
break :blk try std.fs.path.join(gpa, &.{ data_path, file_name });
};
defer if (maybe_data_file_path == null) gpa.free(path);
try generateVersionDataFile(gpa, data_version, path);
}
if (zig_builtin.os.tag == .windows) {
std.log.warn("Running on windows may result in CRLF and LF mismatch", .{});
}
try std.io.getStdOut().writeAll(
\\If you have added a new configuration option and it should be configuration through the config wizard, then edit `src/setup.zig`
\\
try stderr.writeAll(
\\Changing configuration options may also require editing the `package.json` from zls-vscode at https://github.com/zigtools/zls-vscode/blob/master/package.json
\\You can use `zig build gen -Dvscode-config-path=/path/to/output/file.json` to generate the new configuration properties which you can then copy into `package.json`
\\

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,107 +0,0 @@
// Run this in a Chrome developer console.
const builtins = $$("a#toc-Builtin-Functions+ul > li").map(element => {
const anchor = element.querySelector("a").getAttribute("href");
const code = $(`${anchor}+pre > code`).textContent.replace(/(\r\n|\n|\r)/gm, "");
var curr_paragraph = $(`${anchor}+pre+p`);
var doc = "";
var first = true;
while (curr_paragraph.nodeName == "P" || curr_paragraph.nodeName == "PRE") {
if (curr_paragraph.innerHTML == "See also:")
break;
if (!first) {
doc += "\n";
} else {
first = false;
}
if (curr_paragraph.nodeName == "PRE") {
doc += "```zig\n";
curr_paragraph.childNodes[0].childNodes.forEach(elem => {
doc += elem.textContent;
});
doc += "\n```";
} else {
curr_paragraph.childNodes.forEach(elem => {
if (elem.nodeName == "CODE") {
console.log(elem.innerHTML);
doc += "`" + elem.innerHTML.replaceAll(/<span .+?>(.+?)<\/span>/gm, "$1") + "`";
} else
doc += elem.textContent.replace(/(\s\s+)/gm, " ");
});
}
curr_paragraph = curr_paragraph.nextElementSibling;
}
return { "name": anchor.substring(1), "code": code, "documentation": doc };
});
// Take output and paste into a .zig file
console.log(
`const Builtin = struct {
name: []const u8,
signature: []const u8,
snippet: []const u8,
documentation: []const u8,
arguments: []const []const u8,
};
pub const builtins = [_]Builtin{` +
'\n' + builtins.map(builtin => {
// Make a snippet
const first_paren_idx = builtin.code.indexOf('(');
var snippet = builtin.code.substr(0, first_paren_idx + 1);
var rest = builtin.code.substr(first_paren_idx + 1);
var args = [];
if (rest[0] == ')') {
snippet += ')';
} else {
snippet += "${1:"
args.push("");
var arg_idx = 2;
var paren_depth = 1;
var skip_space = false;
for (const char of rest) {
if (char == '(') {
paren_depth += 1;
} else if (char == ')') {
paren_depth -= 1;
if (paren_depth == 0) {
snippet += "})";
break;
}
} else if (char == '"') {
snippet += "\\\"";
args[args.length - 1] += "\\\"";
continue;
} else if (char == ',' && paren_depth == 1) {
snippet += "}, ${" + arg_idx + ':';
arg_idx += 1;
args.push("");
skip_space = true;
continue;
} else if (char == ' ' && skip_space) {
continue;
}
snippet += char;
args[args.length - 1] += char;
skip_space = false;
}
}
return ` .{
.name = "@${builtin.name}",
.signature = "${builtin.code.replaceAll('"', "\\\"")}",
.snippet = "${snippet}",
.documentation =
\\\\${builtin.documentation.split('\n').join("\n \\\\")}
,
.arguments = &.{${args.map(x => "\n \"" + x + "\"").join(",") + ((args.length > 0) ? ",\n " : "")}},
},`;
}).join('\n') + "\n};\n"
);

View File

@ -1,105 +0,0 @@
#!/usr/bin/env python3
import urllib.request
import re
import minify_html
zig_version = 'master'
def fix_ul(s):
l = s.split('<li>')
l.insert(0, '')
return '\n - '.join(l)
url = f'https://raw.githubusercontent.com/ziglang/zig/{zig_version}/doc/langref.html.in'
res = urllib.request.urlopen(url)
page = res.read().decode('utf-8')
print('''const Builtin = struct {
name: []const u8,
signature: []const u8,
snippet: []const u8,
documentation: []const u8,
arguments: []const []const u8,
};
pub const builtins = [_]Builtin{''')
pattern = r'{#header_open\|(@\S+?)#}(.+?){#header_close#}'
for match in re.finditer(pattern, page, re.M | re.S):
blk = match[2].strip(' \n')
name = match[1]
signature = re.search(r'<pre>{#syntax#}(.+?){#endsyntax#}</pre>', blk,
re.M | re.S)[1].replace('\n ', '').replace('"', '\\"')
snippet = name
if f'{name}()' in signature:
params = None
snippet += '()'
else:
params = []
i = signature.index('(') + 1
level = 1
j = i
while i < len(signature):
if signature[i] == '(':
level += 1
elif signature[i] == ')':
level -= 1
if signature[i] == ',' and level == 1:
params.append(signature[j:i])
j = i + 2
if level == 0:
break
i += 1
params.append(signature[j:i])
snippet += '(${'
i = 1
for param in params:
snippet += f'{i}:{param}}}, ${{'
i += 1
snippet = snippet[:-4] + ')'
docs = re.sub(r'{#see_also\|[^#]+#}', '', blk)
docs = re.sub(
r' {#code_begin\|(obj|syntax|(test(\|(call|truncate))?))#}\n', ' <pre>{#syntax#}', docs)
docs = re.sub(
r' {#code_begin\|test_(err|safety)\|[^#]+#}\n', ' <pre>{#syntax#}', docs)
docs = docs.replace(' {#code_release_fast#}\n', '')
docs = docs.replace(' {#code_end#}', '{#endsyntax#}</pre>')
docs = docs.replace('\n{#endsyntax#}</pre>', '{#endsyntax#}</pre>')
docs = minify_html.minify(docs)
prefix = '</pre><p>'
docs = docs[docs.index(prefix)+len(prefix):]
docs = docs.replace('<p>', '\n\n')
docs = re.sub(r'{#(end)?syntax#}', '`', docs)
# @cDefine
docs = re.sub(r'<pre><code[^>]+>([^<]+)</code></pre>', '`\\1`', docs)
docs = re.sub(r'</?code>', '`', docs)
docs = docs.replace('<pre>`', '\n\n```zig\n')
docs = docs.replace('`</pre>', '\n```')
# @setFloatMode
docs = docs.replace('```<', '```\n<')
# @TypeOf
docs = re.sub(r'</?em>', '*', docs)
docs = re.sub(r'<a href=([^>]+)>([^<]+)</a>', '[\\2](\\1)', docs)
docs = re.sub(r'{#link\|([^|#]+)\|([^|#]+)#}',
lambda m: f'[{m[1]}](https://ziglang.org/documentation/{zig_version}/#{m[2].replace(" ","-")})', docs)
docs = re.sub(
r'{#link\|([^|#]+)#}', lambda m: f'[{m[1]}](https://ziglang.org/documentation/{zig_version}/#{m[1].replace(" ","-").replace("@","")})', docs)
docs = re.sub(r'<ul><li>(.+?)</ul>', lambda m: fix_ul(m[1]), docs)
print(' .{')
print(f' .name = "{name}",')
print(f' .signature = "{signature}",')
print(f' .snippet = "{snippet}",')
print(' .documentation =')
for line in docs.splitlines():
print(r' \\' + line)
print(' ,')
if params is None:
print(' .arguments = &.{},')
else:
print(' .arguments = &.{')
for param in params:
print(f' "{param}",')
print(' },')
print(' },')
print('};')

View File

@ -1,3 +1,8 @@
//! DO NOT EDIT
//! If you want to update this file run:
//! `zig build gen -- --generate-version-data master` (requires an internet connection)
//! GENERATED BY src/config_gen/config_gen.zig
const Builtin = struct {
name: []const u8,
signature: []const u8,
@ -58,8 +63,7 @@ pub const builtins = [_]Builtin{
\\ assert(*u32 == *align(@alignOf(u32)) u32);
\\}
\\```
\\
\\The result is a target-specific compile time constant. It is guaranteed to be less than or equal to [@sizeOf(T)](https://ziglang.org/documentation/master/#@sizeOf).
\\The result is a target-specific compile time constant. It is guaranteed to be less than or equal to [@sizeOf(T)](https://ziglang.org/documentation/master/#sizeOf).
,
.arguments = &.{
"comptime T: type",
@ -102,15 +106,16 @@ pub const builtins = [_]Builtin{
\\`T` must be a pointer, a `bool`, a float, an integer or an enum.
\\
\\Supported operations:
\\ - `.Xchg` - stores the operand unmodified. Supports enums, integers and floats.
\\ - `.Add` - for integers, twos complement wraparound addition. Also supports [Floats](https://ziglang.org/documentation/master/#Floats).
\\ - `.Sub` - for integers, twos complement wraparound subtraction. Also supports [Floats](https://ziglang.org/documentation/master/#Floats).
\\ - `.And` - bitwise and
\\ - `.Nand` - bitwise nand
\\ - `.Or` - bitwise or
\\ - `.Xor` - bitwise xor
\\ - `.Max` - stores the operand if it is larger. Supports integers and floats.
\\ - `.Min` - stores the operand if it is smaller. Supports integers and floats.
\\
\\ - `.Xchg` - stores the operand unmodified. Supports enums, integers and floats.
\\ - `.Add` - for integers, twos complement wraparound addition. Also supports [Floats](https://ziglang.org/documentation/master/#Floats).
\\ - `.Sub` - for integers, twos complement wraparound subtraction. Also supports [Floats](https://ziglang.org/documentation/master/#Floats).
\\ - `.And` - bitwise and
\\ - `.Nand` - bitwise nand
\\ - `.Or` - bitwise or
\\ - `.Xor` - bitwise xor
\\ - `.Max` - stores the operand if it is larger. Supports integers and floats.
\\ - `.Min` - stores the operand if it is smaller. Supports integers and floats.
,
.arguments = &.{
"comptime T: type",
@ -148,9 +153,9 @@ pub const builtins = [_]Builtin{
\\Asserts that `@typeInfo(DestType) != .Pointer`. Use `@ptrCast` or `@intToPtr` if you need this.
\\
\\Can be used for these things for example:
\\ - Convert `f32` to `u32` bits
\\ - Convert `i32` to `u32` preserving twos complement
\\
\\ - Convert `f32` to `u32` bits
\\ - Convert `i32` to `u32` preserving twos complement
\\Works at compile-time if `value` is known at compile time. It's a compile error to bitcast a value of undefined layout; this means that, besides the restriction from types which possess dedicated casting builtins (enums, pointers, error sets), bare structs, error unions, slices, optionals, and any other type without a well-defined memory layout, also cannot be used in this operation.
,
.arguments = &.{
@ -278,17 +283,43 @@ pub const builtins = [_]Builtin{
\\
\\```zig
\\const expect = @import("std").testing.expect;
\\
\\test "noinline function call" {
\\ try expect(@call(.auto, add, .{3, 9}) == 12);
\\}
\\
\\fn add(a: i32, b: i32) i32 {
\\ return a + b;
\\}
\\```
\\`@call` allows more flexibility than normal function call syntax does. The `CallModifier` enum is reproduced here:
\\
\\`@call` allows more flexibility than normal function call syntax does. The `CallModifier` enum is reproduced here:</p> {#syntax_block|zig|builtin.CallModifier struct#} pub const CallModifier = enum { /// Equivalent to function call syntax. auto, /// Equivalent to async keyword used with function call syntax. async_kw, /// Prevents tail call optimization. This guarantees that the return /// address will point to the callsite, as opposed to the callsite's /// callsite. If the call is otherwise required to be tail-called /// or inlined, a compile error is emitted instead. never_tail, /// Guarantees that the call will not be inlined. If the call is /// otherwise required to be inlined, a compile error is emitted instead. never_inline, /// Asserts that the function call will not suspend. This allows a /// non-async function to call an async function. no_async, /// Guarantees that the call will be generated with tail call optimization. /// If this is not possible, a compile error is emitted instead. always_tail, /// Guarantees that the call will inlined at the callsite. /// If this is not possible, a compile error is emitted instead. always_inline, /// Evaluates the call at compile-time. If the call cannot be completed at /// compile-time, a compile error is emitted instead. compile_time, }; {#end_syntax_block#}
\\```zig
\\pub const CallModifier = enum {
\\ /// Equivalent to function call syntax.
\\ auto,
\\ /// Equivalent to async keyword used with function call syntax.
\\ async_kw,
\\ /// Prevents tail call optimization. This guarantees that the return
\\ /// address will point to the callsite, as opposed to the callsite's
\\ /// callsite. If the call is otherwise required to be tail-called
\\ /// or inlined, a compile error is emitted instead.
\\ never_tail,
\\ /// Guarantees that the call will not be inlined. If the call is
\\ /// otherwise required to be inlined, a compile error is emitted instead.
\\ never_inline,
\\ /// Asserts that the function call will not suspend. This allows a
\\ /// non-async function to call an async function.
\\ no_async,
\\ /// Guarantees that the call will be generated with tail call optimization.
\\ /// If this is not possible, a compile error is emitted instead.
\\ always_tail,
\\ /// Guarantees that the call will inlined at the callsite.
\\ /// If this is not possible, a compile error is emitted instead.
\\ always_inline,
\\ /// Evaluates the call at compile-time. If the call cannot be completed at
\\ /// compile-time, a compile error is emitted instead.
\\ compile_time,
\\};
\\```
,
.arguments = &.{
"modifier: std.builtin.CallModifier",
@ -303,15 +334,14 @@ pub const builtins = [_]Builtin{
.documentation =
\\This function can only occur inside `@cImport`.
\\
\\This appends `#define $name $value` to the `@cImport` temporary buffer.
\\This appends
\\`#define $name $value`to the `@cImport` temporary buffer.
\\
\\To define without a value, like this:`#define _GNU_SOURCE`
\\To define without a value, like this:
\\
\\Use the void value, like this:
\\`#define _GNU_SOURCE`Use the void value, like this:
\\
\\```zig
\\@cDefine("_GNU_SOURCE", {})
\\```
\\`@cDefine("_GNU_SOURCE", {})`
,
.arguments = &.{
"comptime name: []u8",
@ -330,8 +360,9 @@ pub const builtins = [_]Builtin{
\\Usually you should only have one `@cImport` in your entire application, because it saves the compiler from invoking clang multiple times, and prevents inline functions from being duplicated.
\\
\\Reasons for having multiple `@cImport` expressions would be:
\\ - To avoid a symbol collision, for example if foo.h and bar.h both `#define CONNECTION_COUNT`
\\ - To analyze the C code with different preprocessor defines
\\
\\ - To avoid a symbol collision, for example if foo.h and bar.h both
\\`#define CONNECTION_COUNT` - To analyze the C code with different preprocessor defines
,
.arguments = &.{
"expression",
@ -344,7 +375,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\This function can only occur inside `@cImport`.
\\
\\This appends `#include <$path>\n` to the `c_import` temporary buffer.
\\This appends
\\`#include &lt;$path&gt;\n`to the `c_import` temporary buffer.
,
.arguments = &.{
"comptime path: []u8",
@ -387,7 +419,6 @@ pub const builtins = [_]Builtin{
\\ }
\\}
\\```
\\
\\If you are using cmpxchg in a loop, [@cmpxchgWeak](https://ziglang.org/documentation/master/#cmpxchgWeak) is the better choice, because it can be implemented more efficiently in machine instructions.
\\
\\`T` must be a pointer, a `bool`, a float, an integer or an enum.
@ -408,8 +439,19 @@ pub const builtins = [_]Builtin{
.signature = "@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T",
.snippet = "@cmpxchgWeak(${1:comptime T: type}, ${2:ptr: *T}, ${3:expected_value: T}, ${4:new_value: T}, ${5:success_order: AtomicOrder}, ${6:fail_order: AtomicOrder})",
.documentation =
\\This function performs a weak atomic compare exchange operation. It's the equivalent of this code, except atomic:</p> {#syntax_block|zig|cmpxchgWeakButNotAtomic#} fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T { const old_value = ptr.*; if (old_value == expected_value and usuallyTrueButSometimesFalse()) { ptr.* = new_value; return null; } else { return old_value; } } {#end_syntax_block#}
\\This function performs a weak atomic compare exchange operation. It's the equivalent of this code, except atomic:
\\
\\```zig
\\fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
\\ const old_value = ptr.*;
\\ if (old_value == expected_value and usuallyTrueButSometimesFalse()) {
\\ ptr.* = new_value;
\\ return null;
\\ } else {
\\ return old_value;
\\ }
\\}
\\```
\\If you are using cmpxchg in a loop, the sporadic failure will be no problem, and `cmpxchgWeak` is the better choice, because it can be implemented more efficiently in machine instructions. However if you need a stronger guarantee, use [@cmpxchgStrong](https://ziglang.org/documentation/master/#cmpxchgStrong).
\\
\\`T` must be a pointer, a `bool`, a float, an integer or an enum.
@ -451,22 +493,30 @@ pub const builtins = [_]Builtin{
\\
\\```zig
\\const print = @import("std").debug.print;
\\
\\const num1 = blk: {
\\ var val1: i32 = 99;
\\ @compileLog("comptime val1 = ", val1);
\\ val1 = val1 + 1;
\\ break :blk val1;
\\};
\\
\\test "main" {
\\ @compileLog("comptime in main");
\\
\\ print("Runtime in main, num1 = {}.\n", .{num1});
\\}
\\```
\\If all `@compileLog` calls are removed or not encountered by analysis, the program compiles successfully and the generated executable prints:
\\
\\If all `@compileLog` calls are removed or not encountered by analysis, the program compiles successfully and the generated executable prints:</p> {#code_begin|test|without_compileLog#} const print = @import("std").debug.print; const num1 = blk: { var val1: i32 = 99; val1 = val1 + 1; break :blk val1; }; test "main" { print("Runtime in main, num1 = {}.\n", .{num1}); }`
\\```zig
\\const print = @import("std").debug.print;
\\const num1 = blk: {
\\ var val1: i32 = 99;
\\ val1 = val1 + 1;
\\ break :blk val1;
\\};
\\test "main" {
\\ print("Runtime in main, num1 = {}.\n", .{num1});
\\}
\\```
,
.arguments = &.{
"args: ...",
@ -498,7 +548,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\This function can only occur inside `@cImport`.
\\
\\This appends `#undef $name` to the `@cImport` temporary buffer.
\\This appends
\\`#undef $name`to the `@cImport` temporary buffer.
,
.arguments = &.{
"comptime name: []u8",
@ -553,9 +604,9 @@ pub const builtins = [_]Builtin{
.snippet = "@divExact(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\Exact division. Caller guarantees `denominator != 0` and `@divTrunc(numerator, denominator) * denominator == numerator`.
\\ - `@divExact(6, 3) == 2`
\\ - `@divExact(a, b) * b == a`
\\
\\ - `@divExact(6, 3) == 2`
\\ - `@divExact(a, b) * b == a`
\\For a function that returns a possible error code, use `@import("std").math.divExact`.
,
.arguments = &.{
@ -569,9 +620,9 @@ pub const builtins = [_]Builtin{
.snippet = "@divFloor(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\Floored division. Rounds toward negative infinity. For unsigned integers it is the same as `numerator / denominator`. Caller guarantees `denominator != 0` and `!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1)`.
\\ - `@divFloor(-5, 3) == -2`
\\ - `(@divFloor(a, b) * b) + @mod(a, b) == a`
\\
\\ - `@divFloor(-5, 3) == -2`
\\ - `(@divFloor(a, b) * b) + @mod(a, b) == a`
\\For a function that returns a possible error code, use `@import("std").math.divFloor`.
,
.arguments = &.{
@ -585,9 +636,9 @@ pub const builtins = [_]Builtin{
.snippet = "@divTrunc(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\Truncated division. Rounds toward zero. For unsigned integers it is the same as `numerator / denominator`. Caller guarantees `denominator != 0` and `!(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1)`.
\\ - `@divTrunc(-5, 3) == -1`
\\ - `(@divTrunc(a, b) * b) + @rem(a, b) == a`
\\
\\ - `@divTrunc(-5, 3) == -1`
\\ - `(@divTrunc(a, b) * b) + @rem(a, b) == a`
\\For a function that returns a possible error code, use `@import("std").math.divTrunc`.
,
.arguments = &.{
@ -649,10 +700,10 @@ pub const builtins = [_]Builtin{
.snippet = "@errorToInt(${1:err: anytype})",
.documentation =
\\Supports the following types:
\\ - [The Global Error Set](https://ziglang.org/documentation/master/#The-Global-Error-Set)
\\ - [Error Set Type](https://ziglang.org/documentation/master/#Error-Set-Type)
\\ - [Error Union Type](https://ziglang.org/documentation/master/#Error-Union-Type)
\\
\\ - [The Global Error Set](https://ziglang.org/documentation/master/#The-Global-Error-Set)
\\ - [Error Set Type](https://ziglang.org/documentation/master/#Error-Set-Type)
\\ - [Error Union Type](https://ziglang.org/documentation/master/#Error-Union-Type)
\\Converts an error to the integer representation of an error.
\\
\\It is generally recommended to avoid this cast, as the integer representation of an error is not stable across source code changes.
@ -680,37 +731,28 @@ pub const builtins = [_]Builtin{
.documentation =
\\Creates a symbol in the output object file.
\\
\\`declaration` must be one of two things:
\\ - An identifier (`x`) identifying a [function](https://ziglang.org/documentation/master/#Functions) or a [variable](https://ziglang.org/documentation/master/#Container-Level-Variables).
\\ - Field access (`x.y`) looking up a [function](https://ziglang.org/documentation/master/#Functions) or a [variable](https://ziglang.org/documentation/master/#Container-Level-Variables).
\\`declaration`must be one of two things:
\\
\\This builtin can be called from a [comptime](https://ziglang.org/documentation/master/#comptime) block to conditionally export symbols. When `declaration` is a function with the C calling convention and `options.linkage` is `Strong`, this is equivalent to the `export` keyword used on a function:
\\ - An identifier (`x`) identifying a [function](https://ziglang.org/documentation/master/#Functions) or a [variable](https://ziglang.org/documentation/master/#Container-Level-Variables).
\\ - Field access (`x.y`) looking up a [function](https://ziglang.org/documentation/master/#Functions) or a [variable](https://ziglang.org/documentation/master/#Container-Level-Variables).
\\This builtin can be called from a [comptime](https://ziglang.org/documentation/master/#comptime) block to conditionally export symbols. When
\\`declaration`is a function with the C calling convention and `options.linkage` is `Strong`, this is equivalent to the `export` keyword used on a function:
\\
\\```zig
\\comptime {
\\ @export(internalName, .{ .name = "foo", .linkage = .Strong });
\\}
\\
\\fn internalName() callconv(.C) void {}
\\```
\\
\\This is equivalent to:
\\
\\```zig
\\export fn foo() void {}
\\```
\\
\\`export fn foo() void {}`
\\Note that even when using `export`, the `@"foo"` syntax for [identifiers](https://ziglang.org/documentation/master/#Identifiers) can be used to choose any string for the symbol name:
\\
\\```zig
\\export fn @"A function name that is a complete sentence."() void {}
\\```
\\
\\`export fn @"A function name that is a complete sentence."() void {}`
\\When looking at the resulting object, you can see the symbol is used verbatim:
\\
\\```zig
\\00000000000001f0 T A function name that is a complete sentence.
\\```
\\`00000000000001f0 T A function name that is a complete sentence.`
,
.arguments = &.{
"declaration",
@ -747,7 +789,30 @@ pub const builtins = [_]Builtin{
.signature = "@field(lhs: anytype, comptime field_name: []const u8) (field)",
.snippet = "@field(${1:lhs: anytype}, ${2:comptime field_name: []const u8})",
.documentation =
\\Performs field access by a compile-time string. Works on both fields and declarations.</p> {#code_begin|test|field_decl_access_by_string#} const std = @import("std"); const Point = struct { x: u32, y: u32, pub var z: u32 = 1; }; test "field access by string" { const expect = std.testing.expect; var p = Point{ .x = 0, .y = 0 }; @field(p, "x") = 4; @field(p, "y") = @field(p, "x") + 1; try expect(@field(p, "x") == 4); try expect(@field(p, "y") == 5); } test "decl access by string" { const expect = std.testing.expect; try expect(@field(Point, "z") == 1); @field(Point, "z") = 2; try expect(@field(Point, "z") == 2); }`
\\Performs field access by a compile-time string. Works on both fields and declarations.
\\
\\```zig
\\const std = @import("std");
\\const Point = struct {
\\ x: u32,
\\ y: u32,
\\ pub var z: u32 = 1;
\\};
\\test "field access by string" {
\\ const expect = std.testing.expect;
\\ var p = Point{ .x = 0, .y = 0 };
\\ @field(p, "x") = 4;
\\ @field(p, "y") = @field(p, "x") + 1;
\\ try expect(@field(p, "x") == 4);
\\ try expect(@field(p, "y") == 5);
\\}
\\test "decl access by string" {
\\ const expect = std.testing.expect;
\\ try expect(@field(Point, "z") == 1);
\\ @field(Point, "z") = 2;
\\ try expect(@field(Point, "z") == 2);
\\}
\\```
,
.arguments = &.{
"lhs: anytype",
@ -756,7 +821,7 @@ pub const builtins = [_]Builtin{
},
.{
.name = "@fieldParentPtr",
.signature = "@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8, field_ptr: *T) *ParentType",
.signature = "@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8, field_ptr: *T) *ParentType",
.snippet = "@fieldParentPtr(${1:comptime ParentType: type}, ${2:comptime field_name: []const u8}, ${3:field_ptr: *T})",
.documentation =
\\Given a pointer to a field, returns the base pointer of a struct.
@ -811,7 +876,27 @@ pub const builtins = [_]Builtin{
.signature = "@hasDecl(comptime Container: type, comptime name: []const u8) bool",
.snippet = "@hasDecl(${1:comptime Container: type}, ${2:comptime name: []const u8})",
.documentation =
\\Returns whether or not a [container](https://ziglang.org/documentation/master/#Containers) has a declaration matching `name`.</p> {#code_begin|test|hasDecl#} const std = @import("std"); const expect = std.testing.expect; const Foo = struct { nope: i32, pub var blah = "xxx"; const hi = 1; }; test "@hasDecl" { try expect(@hasDecl(Foo, "blah")); // Even though `hi` is private, @hasDecl returns true because this test is // in the same file scope as Foo. It would return false if Foo was declared // in a different file. try expect(@hasDecl(Foo, "hi")); // @hasDecl is for declarations; not fields. try expect(!@hasDecl(Foo, "nope")); try expect(!@hasDecl(Foo, "nope1234")); }`
\\Returns whether or not a [container](https://ziglang.org/documentation/master/#Containers) has a declaration matching `name`.
\\
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\const Foo = struct {
\\ nope: i32,
\\ pub var blah = "xxx";
\\ const hi = 1;
\\};
\\test "@hasDecl" {
\\ try expect(@hasDecl(Foo, "blah"));
\\ // Even though `hi` is private, @hasDecl returns true because this test is
\\ // in the same file scope as Foo. It would return false if Foo was declared
\\ // in a different file.
\\ try expect(@hasDecl(Foo, "hi"));
\\ // @hasDecl is for declarations; not fields.
\\ try expect(!@hasDecl(Foo, "nope"));
\\ try expect(!@hasDecl(Foo, "nope1234"));
\\}
\\```
,
.arguments = &.{
"comptime Container: type",
@ -848,9 +933,12 @@ pub const builtins = [_]Builtin{
\\`path` can be a relative path or it can be the name of a package. If it is a relative path, it is relative to the file that contains the `@import` function call.
\\
\\The following packages are always available:
\\ - `@import("std")` - Zig Standard Library
\\ - `@import("builtin")` - Target-specific information. The command `zig build-exe --show-builtin` outputs the source to stdout for reference.
\\ - `@import("root")` - Points to the root source file. This is usually `src/main.zig` but it depends on what file is chosen to be built.
\\
\\ - `@import("std")` - Zig Standard Library
\\ - `@import("builtin")` - Target-specific information. The command
\\`zig build-exe --show-builtin`outputs the source to stdout for reference.
\\ - `@import("root")` - Points to the root source file. This is usually
\\`src/main.zig`but it depends on what file is chosen to be built.
,
.arguments = &.{
"comptime path: []u8",
@ -870,7 +958,6 @@ pub const builtins = [_]Builtin{
\\ _ = b;
\\}
\\```
\\
\\To truncate the significant bits of a number out of range of the destination type, use [@truncate](https://ziglang.org/documentation/master/#truncate).
\\
\\If `T` is `comptime_int`, then this is semantically equivalent to [Type Coercion](https://ziglang.org/documentation/master/#Type-Coercion).
@ -897,7 +984,7 @@ pub const builtins = [_]Builtin{
.{
.name = "@intToError",
.signature = "@intToError(value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)) anyerror",
.snippet = "@intToError(${1:value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)})",
.snippet = "@intToError(${1:value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8})",
.documentation =
\\Converts from the integer representation of an error into [The Global Error Set](https://ziglang.org/documentation/master/#The-Global-Error-Set) type.
\\
@ -906,7 +993,7 @@ pub const builtins = [_]Builtin{
\\Attempting to convert an integer that does not correspond to any error results in safety-protected [Undefined Behavior](https://ziglang.org/documentation/master/#Undefined-Behavior).
,
.arguments = &.{
"value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8)",
"value: std.meta.Int(.unsigned, @sizeOf(anyerror) * 8",
},
},
.{
@ -958,10 +1045,7 @@ pub const builtins = [_]Builtin{
\\
\\This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:
\\
\\```zig
\\for (source[0..byte_count]) |b, i| dest[i] = b;
\\```
\\
\\`for (source[0..byte_count]) |b, i| dest[i] = b;`
\\The optimizer is intelligent enough to turn the above snippet into a memcpy.
\\
\\There is also a standard library function for this:
@ -986,10 +1070,7 @@ pub const builtins = [_]Builtin{
\\
\\This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:
\\
\\```zig
\\for (dest[0..byte_count]) |*b| b.* = c;
\\```
\\
\\`for (dest[0..byte_count]) |*b| b.* = c;`
\\The optimizer is intelligent enough to turn the above snippet into a memset.
\\
\\There is also a standard library function for this:
@ -1039,7 +1120,19 @@ pub const builtins = [_]Builtin{
.documentation =
\\This function increases the size of the Wasm memory identified by `index` by `delta` in units of unsigned number of Wasm pages. Note that each Wasm page is 64KB in size. On success, returns previous memory size; on failure, if the allocation fails, returns -1.
\\
\\This function is a low level intrinsic with no safety mechanisms usually useful for allocator designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use something like `@import("std").heap.WasmPageAllocator`.</p> {#code_begin|test|wasmMemoryGrow#} const std = @import("std"); const native_arch = @import("builtin").target.cpu.arch; const expect = std.testing.expect; test "@wasmMemoryGrow" { if (native_arch != .wasm32) return error.SkipZigTest; var prev = @wasmMemorySize(0); try expect(prev == @wasmMemoryGrow(0, 1)); try expect(prev + 1 == @wasmMemorySize(0)); }`
\\This function is a low level intrinsic with no safety mechanisms usually useful for allocator designers targeting Wasm. So unless you are writing a new allocator from scratch, you should use something like `@import("std").heap.WasmPageAllocator`.
\\
\\```zig
\\const std = @import("std");
\\const native_arch = @import("builtin").target.cpu.arch;
\\const expect = std.testing.expect;
\\test "@wasmMemoryGrow" {
\\ if (native_arch != .wasm32) return error.SkipZigTest;
\\ var prev = @wasmMemorySize(0);
\\ try expect(prev == @wasmMemoryGrow(0, 1));
\\ try expect(prev + 1 == @wasmMemorySize(0));
\\}
\\```
,
.arguments = &.{
"index: u32",
@ -1052,9 +1145,9 @@ pub const builtins = [_]Builtin{
.snippet = "@mod(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\Modulus division. For unsigned integers this is the same as `numerator % denominator`. Caller guarantees `denominator > 0`, otherwise the operation will result in a [Remainder Division by Zero](https://ziglang.org/documentation/master/#Remainder-Division-by-Zero) when runtime safety checks are enabled.
\\ - `@mod(-5, 3) == 1`
\\ - `(@divFloor(a, b) * b) + @mod(a, b) == a`
\\
\\ - `@mod(-5, 3) == 1`
\\ - `(@divFloor(a, b) * b) + @mod(a, b) == a`
\\For a function that returns an error code, see `@import("std").math.mod`.
,
.arguments = &.{
@ -1082,8 +1175,9 @@ pub const builtins = [_]Builtin{
\\Invokes the panic handler function. By default the panic handler function calls the public `panic` function exposed in the root source file, or if there is not one specified, the `std.builtin.default_panic` function from `std/builtin.zig`.
\\
\\Generally it is better to use `@import("std").debug.panic`. However, `@panic` can be useful for 2 scenarios:
\\ - From library code, calling the programmer's panic function if they exposed one in the root source file.
\\ - When mixing C and Zig code, calling the canonical panic implementation across multiple .o files.
\\
\\ - From library code, calling the programmer's panic function if they exposed one in the root source file.
\\ - When mixing C and Zig code, calling the canonical panic implementation across multiple .o files.
,
.arguments = &.{
"message: []const u8",
@ -1115,7 +1209,32 @@ pub const builtins = [_]Builtin{
\\
\\The `ptr` argument may be any pointer type and determines the memory address to prefetch. This function does not dereference the pointer, it is perfectly legal to pass a pointer to invalid memory to this function and no illegal behavior will result.
\\
\\The `options` argument is the following struct:</p> {#code_begin|syntax|builtin#} /// This data structure is used by the Zig language code generation and /// therefore must be kept in sync with the compiler implementation. pub const PrefetchOptions = struct { /// Whether the prefetch should prepare for a read or a write. rw: Rw = .read, /// 0 means no temporal locality. That is, the data can be immediately /// dropped from the cache after it is accessed. /// /// 3 means high temporal locality. That is, the data should be kept in /// the cache as it is likely to be accessed again soon. locality: u2 = 3, /// The cache that the prefetch should be preformed on. cache: Cache = .data, pub const Rw = enum { read, write, }; pub const Cache = enum { instruction, data, }; };`
\\The `options` argument is the following struct:
\\
\\```zig
\\/// This data structure is used by the Zig language code generation and
\\/// therefore must be kept in sync with the compiler implementation.
\\pub const PrefetchOptions = struct {
\\ /// Whether the prefetch should prepare for a read or a write.
\\ rw: Rw = .read,
\\ /// 0 means no temporal locality. That is, the data can be immediately
\\ /// dropped from the cache after it is accessed.
\\ ///
\\ /// 3 means high temporal locality. That is, the data should be kept in
\\ /// the cache as it is likely to be accessed again soon.
\\ locality: u2 = 3,
\\ /// The cache that the prefetch should be preformed on.
\\ cache: Cache = .data,
\\ pub const Rw = enum {
\\ read,
\\ write,
\\ };
\\ pub const Cache = enum {
\\ instruction,
\\ data,
\\ };
\\};
\\```
,
.arguments = &.{
"ptr: anytype",
@ -1155,9 +1274,9 @@ pub const builtins = [_]Builtin{
.snippet = "@rem(${1:numerator: T}, ${2:denominator: T})",
.documentation =
\\Remainder division. For unsigned integers this is the same as `numerator % denominator`. Caller guarantees `denominator > 0`, otherwise the operation will result in a [Remainder Division by Zero](https://ziglang.org/documentation/master/#Remainder-Division-by-Zero) when runtime safety checks are enabled.
\\ - `@rem(-5, 3) == -2`
\\ - `(@divTrunc(a, b) * b) + @rem(a, b) == a`
\\
\\ - `@rem(-5, 3) == -2`
\\ - `(@divTrunc(a, b) * b) + @rem(a, b) == a`
\\For a function that returns an error code, see `@import("std").math.rem`.
,
.arguments = &.{
@ -1225,16 +1344,16 @@ pub const builtins = [_]Builtin{
\\
\\Example:
\\
\\```zig
\\test "foo" {
\\ comptime {
\\ var i = 0;
\\ while (i < 1001) : (i += 1) {}
\\1001) : (i += 1) {}
\\ }
\\}
\\```
\\Now we use `@setEvalBranchQuota`:
\\
\\Now we use `@setEvalBranchQuota`:</p> {#code_begin|test|setEvalBranchQuota#} test "foo" { comptime { @setEvalBranchQuota(1001); var i = 0; while (i < 1001) : (i += 1) {} } }`
\\1001) : (i += 1) {}
\\ }
\\}
\\```
,
.arguments = &.{
"comptime new_quota: u32",
@ -1253,16 +1372,16 @@ pub const builtins = [_]Builtin{
\\ Optimized,
\\};
\\```
\\
\\ - `Strict` (default) - Floating point operations follow strict IEEE compliance.
\\ - `Optimized` - Floating point operations may do all of the following: <ul>
\\ - Assume the arguments and result are not NaN. Optimizations are required to retain defined behavior over NaNs, but the value of the result is undefined.
\\ - Assume the arguments and result are not +/-Inf. Optimizations are required to retain defined behavior over +/-Inf, but the value of the result is undefined.
\\ - Treat the sign of a zero argument or result as insignificant.
\\ - Use the reciprocal of an argument rather than perform division.
\\ - Perform floating-point contraction (e.g. fusing a multiply followed by an addition into a fused multiply-add).
\\ - Perform algebraically equivalent transformations that may change results in floating point (e.g. reassociate). This is equivalent to `-ffast-math` in GCC.</ul>
\\
\\ - `Strict` (default) - Floating point operations follow strict IEEE compliance.
\\ - `Optimized` - Floating point operations may do all of the following:
\\ - Assume the arguments and result are not NaN. Optimizations are required to retain defined behavior over NaNs, but the value of the result is undefined.
\\ - Assume the arguments and result are not +/-Inf. Optimizations are required to retain defined behavior over +/-Inf, but the value of the result is undefined.
\\ - Treat the sign of a zero argument or result as insignificant.
\\ - Use the reciprocal of an argument rather than perform division.
\\ - Perform floating-point contraction (e.g. fusing a multiply followed by an addition into a fused multiply-add).
\\ - Perform algebraically equivalent transformations that may change results in floating point (e.g. reassociate).
\\This is equivalent to
\\`-ffast-math`in GCC.
\\The floating point mode is inherited by child scopes, and can be overridden in any scope. You can set the floating point mode in a struct or module scope by using a comptime block.
,
.arguments = &.{
@ -1288,7 +1407,6 @@ pub const builtins = [_]Builtin{
\\ @setRuntimeSafety(true);
\\ var x: u8 = 255;
\\ x += 1;
\\
\\ {
\\ // The value can be overridden at any scope. So here integer overflow
\\ // would not be caught in any build mode.
@ -1299,8 +1417,9 @@ pub const builtins = [_]Builtin{
\\ }
\\}
\\```
\\
\\Note: it is [planned](https://github.com/ziglang/zig/issues/978) to replace `@setRuntimeSafety` with `@optimizeFor`
\\Note: it is
\\[planned](https://github.com/ziglang/zig/issues/978)to replace `@setRuntimeSafety` with
\\`@optimizeFor`
,
.arguments = &.{
"comptime safety_on: bool",
@ -1311,7 +1430,7 @@ pub const builtins = [_]Builtin{
.signature = "@shlExact(value: T, shift_amt: Log2T) T",
.snippet = "@shlExact(${1:value: T}, ${2:shift_amt: Log2T})",
.documentation =
\\Performs the left shift operation (`<<`). For unsigned integers, the result is [undefined](https://ziglang.org/documentation/master/#undefined) if any 1 bits are shifted out. For signed integers, the result is [undefined](https://ziglang.org/documentation/master/#undefined) if any bits that disagree with the resultant sign bit are shifted out.
\\`). For unsigned integers, the result is [undefined](https://ziglang.org/documentation/master/#undefined) if any 1 bits are shifted out. For signed integers, the result is [undefined](https://ziglang.org/documentation/master/#undefined) if any bits that disagree with the resultant sign bit are shifted out.
\\
\\The type of `shift_amt` is an unsigned integer with `log2(@typeInfo(T).Int.bits)` bits. This is because `shift_amt >= @typeInfo(T).Int.bits` is undefined behavior.
,
@ -1325,7 +1444,7 @@ pub const builtins = [_]Builtin{
.signature = "@shlWithOverflow(a: anytype, shift_amt: Log2T) struct { @TypeOf(a), u1 }",
.snippet = "@shlWithOverflow(${1:a: anytype}, ${2:shift_amt: Log2T})",
.documentation =
\\Performs `a << b` and returns a tuple with the result and a possible overflow bit.
\\b` and returns a tuple with the result and a possible overflow bit.
\\
\\The type of `shift_amt` is an unsigned integer with `log2(@typeInfo(@TypeOf(a)).Int.bits)` bits. This is because `shift_amt >= @typeInfo(@TypeOf(a)).Int.bits` is undefined behavior.
,
@ -1363,7 +1482,25 @@ pub const builtins = [_]Builtin{
\\
\\If `a` or `b` is `undefined`, it is equivalent to a vector of all `undefined` with the same length as the other vector. If both vectors are `undefined`, `@shuffle` returns a vector with all elements `undefined`.
\\
\\`E` must be an [integer](https://ziglang.org/documentation/master/#Integers), [float](https://ziglang.org/documentation/master/#Floats), [pointer](https://ziglang.org/documentation/master/#Pointers), or `bool`. The mask may be any vector length, and its length determines the result length.</p> {#code_begin|test|vector_shuffle#} const std = @import("std"); const expect = std.testing.expect; test "vector @shuffle" { const a = @Vector(7, u8){ 'o', 'l', 'h', 'e', 'r', 'z', 'w' }; const b = @Vector(4, u8){ 'w', 'd', '!', 'x' }; // To shuffle within a single vector, pass undefined as the second argument. // Notice that we can re-order, duplicate, or omit elements of the input vector const mask1 = @Vector(5, i32){ 2, 3, 1, 1, 0 }; const res1: @Vector(5, u8) = @shuffle(u8, a, undefined, mask1); try expect(std.mem.eql(u8, &@as([5]u8, res1), "hello")); // Combining two vectors const mask2 = @Vector(6, i32){ -1, 0, 4, 1, -2, -3 }; const res2: @Vector(6, u8) = @shuffle(u8, a, b, mask2); try expect(std.mem.eql(u8, &@as([6]u8, res2), "world!")); }`
\\`E` must be an [integer](https://ziglang.org/documentation/master/#Integers), [float](https://ziglang.org/documentation/master/#Floats), [pointer](https://ziglang.org/documentation/master/#Pointers), or `bool`. The mask may be any vector length, and its length determines the result length.
\\
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\test "vector @shuffle" {
\\ const a = @Vector(7, u8){ 'o', 'l', 'h', 'e', 'r', 'z', 'w' };
\\ const b = @Vector(4, u8){ 'w', 'd', '!', 'x' };
\\ // To shuffle within a single vector, pass undefined as the second argument.
\\ // Notice that we can re-order, duplicate, or omit elements of the input vector
\\ const mask1 = @Vector(5, i32){ 2, 3, 1, 1, 0 };
\\ const res1: @Vector(5, u8) = @shuffle(u8, a, undefined, mask1);
\\ try expect(std.mem.eql(u8, &@as([5]u8, res1), "hello"));
\\ // Combining two vectors
\\ const mask2 = @Vector(6, i32){ -1, 0, 4, 1, -2, -3 };
\\ const res2: @Vector(6, u8) = @shuffle(u8, a, b, mask2);
\\ try expect(std.mem.eql(u8, &@as([6]u8, res2), "world!"));
\\}
\\```
,
.arguments = &.{
"comptime E: type",
@ -1392,8 +1529,18 @@ pub const builtins = [_]Builtin{
.signature = "@splat(comptime len: u32, scalar: anytype) @Vector(len, @TypeOf(scalar))",
.snippet = "@splat(${1:comptime len: u32}, ${2:scalar: anytype})",
.documentation =
\\Produces a vector of length `len` where each element is the value `scalar`:</p> {#code_begin|test|vector_splat#} const std = @import("std"); const expect = std.testing.expect; test "vector @splat" { const scalar: u32 = 5; const result = @splat(4, scalar); comptime try expect(@TypeOf(result) == @Vector(4, u32)); try expect(std.mem.eql(u32, &@as([4]u32, result), &[_]u32{ 5, 5, 5, 5 })); }`
\\Produces a vector of length `len` where each element is the value `scalar`:
\\
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\test "vector @splat" {
\\ const scalar: u32 = 5;
\\ const result = @splat(4, scalar);
\\ comptime try expect(@TypeOf(result) == @Vector(4, u32));
\\ try expect(std.mem.eql(u32, &@as([4]u32, result), &[_]u32{ 5, 5, 5, 5 }));
\\}
\\```
\\`scalar` must be an [integer](https://ziglang.org/documentation/master/#Integers), [bool](https://ziglang.org/documentation/master/#Primitive-Types), [float](https://ziglang.org/documentation/master/#Floats), or [pointer](https://ziglang.org/documentation/master/#Pointers).
,
.arguments = &.{
@ -1406,14 +1553,29 @@ pub const builtins = [_]Builtin{
.signature = "@reduce(comptime op: std.builtin.ReduceOp, value: anytype) E",
.snippet = "@reduce(${1:comptime op: std.builtin.ReduceOp}, ${2:value: anytype})",
.documentation =
\\Transforms a [vector](https://ziglang.org/documentation/master/#Vectors) into a scalar value (of type `E`) by performing a sequential horizontal reduction of its elements using the specified operator `op`.
\\Transforms a [vector](https://ziglang.org/documentation/master/#Vectors) into a scalar value (of type
\\`E`) by performing a sequential horizontal reduction of its elements using the specified operator `op`.
\\
\\Not every operator is available for every vector element type:
\\ - Every operator is available for [integer](https://ziglang.org/documentation/master/#Integers) vectors.
\\ - `.And`, `.Or`, `.Xor` are additionally available for `bool` vectors,
\\ - `.Min`, `.Max`, `.Add`, `.Mul` are additionally available for [floating point](https://ziglang.org/documentation/master/#Floats) vectors,
\\
\\Note that `.Add` and `.Mul` reductions on integral types are wrapping; when applied on floating point types the operation associativity is preserved, unless the float mode is set to `Optimized`.</p> {#code_begin|test|vector_reduce#} const std = @import("std"); const expect = std.testing.expect; test "vector @reduce" { const value = @Vector(4, i32){ 1, -1, 1, -1 }; const result = value > @splat(4, @as(i32, 0)); // result is { true, false, true, false }; comptime try expect(@TypeOf(result) == @Vector(4, bool)); const is_all_true = @reduce(.And, result); comptime try expect(@TypeOf(is_all_true) == bool); try expect(is_all_true == false); }`
\\ - Every operator is available for [integer](https://ziglang.org/documentation/master/#Integers) vectors.
\\ - `.And`, `.Or`, `.Xor` are additionally available for `bool` vectors,
\\ - `.Min`, `.Max`, `.Add`, `.Mul` are additionally available for [floating point](https://ziglang.org/documentation/master/#Floats) vectors,
\\Note that `.Add` and `.Mul` reductions on integral types are wrapping; when applied on floating point types the operation associativity is preserved, unless the float mode is set to `Optimized`.
\\
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\test "vector @reduce" {
\\ const value = @Vector(4, i32){ 1, -1, 1, -1 };
\\ const result = value > @splat(4, @as(i32, 0));
\\ // result is { true, false, true, false };
\\ comptime try expect(@TypeOf(result) == @Vector(4, bool));
\\ const is_all_true = @reduce(.And, result);
\\ comptime try expect(@TypeOf(is_all_true) == bool);
\\ try expect(is_all_true == false);
\\}
\\```
,
.arguments = &.{
"comptime op: std.builtin.ReduceOp",
@ -1425,7 +1587,22 @@ pub const builtins = [_]Builtin{
.signature = "@src() std.builtin.SourceLocation",
.snippet = "@src()",
.documentation =
\\Returns a `SourceLocation` struct representing the function's name and location in the source code. This must be called in a function.</p> {#code_begin|test|source_location#} const std = @import("std"); const expect = std.testing.expect; test "@src" { try doTheTest(); } fn doTheTest() !void { const src = @src(); try expect(src.line == 9); try expect(src.column == 17); try expect(std.mem.endsWith(u8, src.fn_name, "doTheTest")); try expect(std.mem.endsWith(u8, src.file, "source_location.zig")); }`
\\Returns a `SourceLocation` struct representing the function's name and location in the source code. This must be called in a function.
\\
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\test "@src" {
\\ try doTheTest();
\\}
\\fn doTheTest() !void {
\\ const src = @src();
\\ try expect(src.line == 9);
\\ try expect(src.column == 17);
\\ try expect(std.mem.endsWith(u8, src.fn_name, "doTheTest"));
\\ try expect(std.mem.endsWith(u8, src.file, "source_location.zig"));
\\}
\\```
,
.arguments = &.{},
},
@ -1436,7 +1613,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Performs the square root of a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1449,7 +1627,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Sine trigonometric function on a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1462,7 +1641,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Cosine trigonometric function on a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1475,7 +1655,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Tangent trigonometric function on a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1488,7 +1669,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Base-e exponential function on a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1501,7 +1683,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1514,7 +1697,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1527,7 +1711,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1540,7 +1725,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1553,7 +1739,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Returns the absolute value of a floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1566,7 +1753,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Returns the largest integral value not greater than the given floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1579,7 +1767,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Returns the smallest integral value not less than the given floating point number. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1592,7 +1781,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Rounds the given floating point number to an integer, towards zero. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1605,7 +1795,8 @@ pub const builtins = [_]Builtin{
.documentation =
\\Rounds the given floating point number to an integer, away from zero. Uses a dedicated hardware instruction when available.
\\
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that [some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
\\Supports [Floats](https://ziglang.org/documentation/master/#Floats) and [Vectors](https://ziglang.org/documentation/master/#Vectors) of floats, with the caveat that
\\[some float operations are not yet implemented for all float types](https://github.com/ziglang/zig/issues/4026).
,
.arguments = &.{
"value: anytype",
@ -1641,8 +1832,26 @@ pub const builtins = [_]Builtin{
.signature = "@This() type",
.snippet = "@This()",
.documentation =
\\Returns the innermost struct, enum, or union that this function call is inside. This can be useful for an anonymous struct that needs to refer to itself:</p> {#code_begin|test|this_innermost#} const std = @import("std"); const expect = std.testing.expect; test "@This()" { var items = [_]i32{ 1, 2, 3, 4 }; const list = List(i32){ .items = items[0..] }; try expect(list.length() == 4); } fn List(comptime T: type) type { return struct { const Self = @This(); items: []T, fn length(self: Self) usize { return self.items.len; } }; }`
\\Returns the innermost struct, enum, or union that this function call is inside. This can be useful for an anonymous struct that needs to refer to itself:
\\
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\test "@This()" {
\\ var items = [_]i32{ 1, 2, 3, 4 };
\\ const list = List(i32){ .items = items[0..] };
\\ try expect(list.length() == 4);
\\}
\\fn List(comptime T: type) type {
\\ return struct {
\\ const Self = @This();
\\ items: []T,
\\ fn length(self: Self) usize {
\\ return self.items.len;
\\ }
\\ };
\\}
\\```
\\When `@This()` is used at file scope, it returns a reference to the struct that corresponds to the current file.
,
.arguments = &.{},
@ -1661,14 +1870,12 @@ pub const builtins = [_]Builtin{
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\
\\test "integer truncation" {
\\ var a: u16 = 0xabcd;
\\ var b: u8 = @truncate(u8, a);
\\ try expect(b == 0xcd);
\\}
\\```
\\
\\Use [@intCast](https://ziglang.org/documentation/master/#intCast) to convert numbers guaranteed to fit the destination type.
,
.arguments = &.{
@ -1684,29 +1891,29 @@ pub const builtins = [_]Builtin{
\\This function is the inverse of [@typeInfo](https://ziglang.org/documentation/master/#typeInfo). It reifies type information into a `type`.
\\
\\It is available for the following types:
\\ - `type`
\\ - `noreturn`
\\ - `void`
\\ - `bool`
\\ - [Integers](https://ziglang.org/documentation/master/#Integers) - The maximum bit count for an integer type is `65535`.
\\ - [Floats](https://ziglang.org/documentation/master/#Floats)
\\ - [Pointers](https://ziglang.org/documentation/master/#Pointers)
\\ - `comptime_int`
\\ - `comptime_float`
\\ - `@TypeOf(undefined)`
\\ - `@TypeOf(null)`
\\ - [Arrays](https://ziglang.org/documentation/master/#Arrays)
\\ - [Optionals](https://ziglang.org/documentation/master/#Optionals)
\\ - [Error Set Type](https://ziglang.org/documentation/master/#Error-Set-Type)
\\ - [Error Union Type](https://ziglang.org/documentation/master/#Error-Union-Type)
\\ - [Vectors](https://ziglang.org/documentation/master/#Vectors)
\\ - [opaque](https://ziglang.org/documentation/master/#opaque)
\\ - `anyframe`
\\ - [struct](https://ziglang.org/documentation/master/#struct)
\\ - [enum](https://ziglang.org/documentation/master/#enum)
\\ - [Enum Literals](https://ziglang.org/documentation/master/#Enum-Literals)
\\ - [union](https://ziglang.org/documentation/master/#union)
\\
\\ - `type`
\\ - `noreturn`
\\ - `void`
\\ - `bool`
\\ - [Integers](https://ziglang.org/documentation/master/#Integers) - The maximum bit count for an integer type is `65535`.
\\ - [Floats](https://ziglang.org/documentation/master/#Floats)
\\ - [Pointers](https://ziglang.org/documentation/master/#Pointers)
\\ - `comptime_int`
\\ - `comptime_float`
\\ - `@TypeOf(undefined)`
\\ - `@TypeOf(null)`
\\ - [Arrays](https://ziglang.org/documentation/master/#Arrays)
\\ - [Optionals](https://ziglang.org/documentation/master/#Optionals)
\\ - [Error Set Type](https://ziglang.org/documentation/master/#Error-Set-Type)
\\ - [Error Union Type](https://ziglang.org/documentation/master/#Error-Union-Type)
\\ - [Vectors](https://ziglang.org/documentation/master/#Vectors)
\\ - [opaque](https://ziglang.org/documentation/master/#opaque)
\\ - `anyframe`
\\ - [struct](https://ziglang.org/documentation/master/#struct)
\\ - [enum](https://ziglang.org/documentation/master/#enum)
\\ - [Enum Literals](https://ziglang.org/documentation/master/#Enum-Literals)
\\ - [union](https://ziglang.org/documentation/master/#union)
\\`@Type` is not available for [Functions](https://ziglang.org/documentation/master/#Functions).
,
.arguments = &.{
@ -1746,7 +1953,23 @@ pub const builtins = [_]Builtin{
.documentation =
\\`@TypeOf` is a special builtin function that takes any (nonzero) number of expressions as parameters and returns the type of the result, using [Peer Type Resolution](https://ziglang.org/documentation/master/#Peer-Type-Resolution).
\\
\\The expressions are evaluated, however they are guaranteed to have no *runtime* side-effects:</p> {#code_begin|test|no_runtime_side_effects#} const std = @import("std"); const expect = std.testing.expect; test "no runtime side effects" { var data: i32 = 0; const T = @TypeOf(foo(i32, &data)); comptime try expect(T == i32); try expect(data == 0); } fn foo(comptime T: type, ptr: *T) T { ptr.* += 1; return ptr.*; }`
\\The expressions are evaluated, however they are guaranteed to have no
\\**runtime** side-effects:
\\
\\```zig
\\const std = @import("std");
\\const expect = std.testing.expect;
\\test "no runtime side effects" {
\\ var data: i32 = 0;
\\ const T = @TypeOf(foo(i32, &data));
\\ comptime try expect(T == i32);
\\ try expect(data == 0);
\\}
\\fn foo(comptime T: type, ptr: *T) T {
\\ ptr.* += 1;
\\ return ptr.*;
\\}
\\```
,
.arguments = &.{
"...",
@ -1780,3 +2003,5 @@ pub const builtins = [_]Builtin{
},
},
};
// DO NOT EDIT