authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2016-08-16 22:42:50-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2016-08-16 22:42:50-07:00
log37d167f6e0e26e8dc57950cb0fa1bfa630036521
tree8b947d065ef12b189cb7a4c880c0009e7a6cd2b8
parent0ae9023832584e256aa3b6df0f0829026141d21a

std: conform to style guidelines


26 files changed, 707 insertions(+), 686 deletions(-)

doc/style.md+59-3
...@@ -5,12 +5,68 @@ this documentation along with the compiler in order to provide a point of...@@ -5,12 +5,68 @@ this documentation along with the compiler in order to provide a point of
5reference, should anyone wish to point to an authority on agreed upon Zig5reference, should anyone wish to point to an authority on agreed upon Zig
6coding style.6coding style.
77
8## Whitespace
9
8 * 4 space indentation10 * 4 space indentation
9 * `camelCaseFunctionName`
10 * `TitleCaseTypeName`
11 * `snake_case_variable_name`
12 * Open braces on same line, unless you need to wrap.11 * Open braces on same line, unless you need to wrap.
13 * If a list of things is longer than 2, put each item on its own line and12 * If a list of things is longer than 2, put each item on its own line and
14 exercise the abilty to put an extra comma at the end.13 exercise the abilty to put an extra comma at the end.
14 * Line length: aim for 100; use common sense.
15
16## Names
17
18Roughly speaking: `camelCaseFunctionName`, `TitleCaseTypeName`,
19`snake_case_variable_name`. More precisely:
20
21 * If `x` is a `struct` (or an alias of a `struct`), then `x` should be `TitleCase`.
22 * If `x` otherwise identifies a type, `x` should have `snake_case`.
23 * If `x` is callable, and `x`'s return type is `type`, then `x` should be `TitleCase`.
24 * If `x` is otherwise callable, then `x` should be `camelCase`.
25 * Otherwise, `x` should be `snake_case`.
26
27Acronyms, initialisms, proper nouns, or any other word that has capitalization
28rules in written English are subject to naming conventions just like any other
29word. Even acronyms that are only 2 letters long are subject to these
30conventions.
31
32Examples:
33
34```zig
35const namespace_name = @import("dir_name/file_name.zig");
36var global_var: i32;
37const const_name = 42;
38const primitive_type_alias = f32;
39const string_alias = []u8;
40
41struct StructName {}
42const StructAlias = StructName;
43
44fn functionName(param_name: TypeName) {
45 var functionPointer = functionName;
46 functionPointer();
47 functionPointer = otherFunction;
48 functionPointer();
49}
50const functionAlias = functionName;
51
52fn ListTemplateFunction(ChildType: type, inline fixed_size: usize) -> type {
53 struct ShortList(T: type, n: usize) {
54 field_name: [n]T,
55 fn methodName() {}
56 }
57 return List(ChildType, fixed_size);
58}
59
60// The word XML loses its casing when used in Zig identifiers.
61const xml_document =
62 \\<?xml version="1.0" encoding="UTF-8"?>
63 \\<document>
64 \\</document>
65 ;
66struct XmlParser {}
67
68// The initials BE (Big Endian) are just another word in Zig identifier names.
69fn readU32Be() -> u32 {}
70```
1571
16See Zig standard library for examples.72See Zig standard library for examples.
example/cat/main.zig+3-3
...@@ -16,7 +16,7 @@ pub fn main(args: [][]u8) -> %void {...@@ -16,7 +16,7 @@ pub fn main(args: [][]u8) -> %void {
16 } else {16 } else {
17 var is = io.InStream.open(arg) %% |err| {17 var is = io.InStream.open(arg) %% |err| {
18 %%io.stderr.printf("Unable to open file: ");18 %%io.stderr.printf("Unable to open file: ");
19 %%io.stderr.printf(@err_name(err));19 %%io.stderr.printf(@errName(err));
20 %%io.stderr.printf("\n");20 %%io.stderr.printf("\n");
21 return err;21 return err;
22 };22 };
...@@ -45,7 +45,7 @@ fn cat_stream(is: io.InStream) -> %void {...@@ -45,7 +45,7 @@ fn cat_stream(is: io.InStream) -> %void {
45 while (true) {45 while (true) {
46 const bytes_read = is.read(buf) %% |err| {46 const bytes_read = is.read(buf) %% |err| {
47 %%io.stderr.printf("Unable to read from stream: ");47 %%io.stderr.printf("Unable to read from stream: ");
48 %%io.stderr.printf(@err_name(err));48 %%io.stderr.printf(@errName(err));
49 %%io.stderr.printf("\n");49 %%io.stderr.printf("\n");
50 return err;50 return err;
51 };51 };
...@@ -56,7 +56,7 @@ fn cat_stream(is: io.InStream) -> %void {...@@ -56,7 +56,7 @@ fn cat_stream(is: io.InStream) -> %void {
5656
57 io.stdout.write(buf[0...bytes_read]) %% |err| {57 io.stdout.write(buf[0...bytes_read]) %% |err| {
58 %%io.stderr.printf("Unable to write to stdout: ");58 %%io.stderr.printf("Unable to write to stdout: ");
59 %%io.stderr.printf(@err_name(err));59 %%io.stderr.printf(@errName(err));
60 %%io.stderr.printf("\n");60 %%io.stderr.printf("\n");
61 return err;61 return err;
62 };62 };
example/guess_number/main.zig+5-4
...@@ -6,11 +6,12 @@ const os = std.os;...@@ -6,11 +6,12 @@ const os = std.os;
6pub fn main(args: [][]u8) -> %void {6pub fn main(args: [][]u8) -> %void {
7 %%io.stdout.printf("Welcome to the Guess Number Game in Zig.\n");7 %%io.stdout.printf("Welcome to the Guess Number Game in Zig.\n");
88
9 var seed: [@sizeof(usize)]u8 = undefined;9 var seed: [@sizeOf(usize)]u8 = undefined;
10 %%os.get_random_bytes(seed);10 %%os.get_random_bytes(seed);
11 var rand = Rand.init(([]usize)(seed)[0]);11 var rand: Rand = undefined;
12 rand.init(([]usize)(seed)[0]);
1213
13 const answer = rand.range_unsigned(u8, 0, 100) + 1;14 const answer = rand.rangeUnsigned(u8, 0, 100) + 1;
1415
15 while (true) {16 while (true) {
16 %%io.stdout.printf("\nGuess a number between 1 and 100: ");17 %%io.stdout.printf("\nGuess a number between 1 and 100: ");
...@@ -21,7 +22,7 @@ pub fn main(args: [][]u8) -> %void {...@@ -21,7 +22,7 @@ pub fn main(args: [][]u8) -> %void {
21 return err;22 return err;
22 };23 };
2324
24 const guess = io.parse_unsigned(u8, line_buf[0...line_len - 1], 10) %% {25 const guess = io.parseUnsigned(u8, line_buf[0...line_len - 1], 10) %% {
25 %%io.stdout.printf("Invalid number.\n");26 %%io.stdout.printf("Invalid number.\n");
26 continue;27 continue;
27 };28 };
src/analyze.cpp+1-1
...@@ -5206,7 +5206,7 @@ static TypeTableEntry *analyze_builtin_fn_call_expr(CodeGen *g, ImportTableEntry...@@ -5206,7 +5206,7 @@ static TypeTableEntry *analyze_builtin_fn_call_expr(CodeGen *g, ImportTableEntry
5206 case TypeTableEntryIdNamespace:5206 case TypeTableEntryIdNamespace:
5207 case TypeTableEntryIdGenericFn:5207 case TypeTableEntryIdGenericFn:
5208 add_node_error(g, expr_node,5208 add_node_error(g, expr_node,
5209 buf_sprintf("type '%s' not eligible for @typeof", buf_ptr(&type_entry->name)));5209 buf_sprintf("type '%s' not eligible for @typeOf", buf_ptr(&type_entry->name)));
5210 return g->builtin_types.entry_invalid;5210 return g->builtin_types.entry_invalid;
5211 case TypeTableEntryIdMetaType:5211 case TypeTableEntryIdMetaType:
5212 case TypeTableEntryIdVoid:5212 case TypeTableEntryIdVoid:
src/codegen.cpp+23-23
...@@ -4642,7 +4642,7 @@ static void define_builtin_fns(CodeGen *g) {...@@ -4642,7 +4642,7 @@ static void define_builtin_fns(CodeGen *g) {
4642 }4642 }
4643 {4643 {
4644 BuiltinFnEntry *builtin_fn = create_builtin_fn_with_arg_count(g, BuiltinFnIdReturnAddress,4644 BuiltinFnEntry *builtin_fn = create_builtin_fn_with_arg_count(g, BuiltinFnIdReturnAddress,
4645 "return_address", 0);4645 "returnAddress", 0);
4646 builtin_fn->return_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);4646 builtin_fn->return_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);
46474647
4648 LLVMTypeRef fn_type = LLVMFunctionType(builtin_fn->return_type->type_ref,4648 LLVMTypeRef fn_type = LLVMFunctionType(builtin_fn->return_type->type_ref,
...@@ -4652,7 +4652,7 @@ static void define_builtin_fns(CodeGen *g) {...@@ -4652,7 +4652,7 @@ static void define_builtin_fns(CodeGen *g) {
4652 }4652 }
4653 {4653 {
4654 BuiltinFnEntry *builtin_fn = create_builtin_fn_with_arg_count(g, BuiltinFnIdFrameAddress,4654 BuiltinFnEntry *builtin_fn = create_builtin_fn_with_arg_count(g, BuiltinFnIdFrameAddress,
4655 "frame_address", 0);4655 "frameAddress", 0);
4656 builtin_fn->return_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);4656 builtin_fn->return_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);
46574657
4658 LLVMTypeRef fn_type = LLVMFunctionType(builtin_fn->return_type->type_ref,4658 LLVMTypeRef fn_type = LLVMFunctionType(builtin_fn->return_type->type_ref,
...@@ -4708,33 +4708,33 @@ static void define_builtin_fns(CodeGen *g) {...@@ -4708,33 +4708,33 @@ static void define_builtin_fns(CodeGen *g) {
47084708
4709 g->memset_fn_val = builtin_fn->fn_val;4709 g->memset_fn_val = builtin_fn->fn_val;
4710 }4710 }
4711 create_builtin_fn_with_arg_count(g, BuiltinFnIdSizeof, "sizeof", 1);4711 create_builtin_fn_with_arg_count(g, BuiltinFnIdSizeof, "sizeOf", 1);
4712 create_builtin_fn_with_arg_count(g, BuiltinFnIdAlignof, "alignof", 1);4712 create_builtin_fn_with_arg_count(g, BuiltinFnIdAlignof, "alignOf", 1);
4713 create_builtin_fn_with_arg_count(g, BuiltinFnIdMaxValue, "max_value", 1);4713 create_builtin_fn_with_arg_count(g, BuiltinFnIdMaxValue, "maxValue", 1);
4714 create_builtin_fn_with_arg_count(g, BuiltinFnIdMinValue, "min_value", 1);4714 create_builtin_fn_with_arg_count(g, BuiltinFnIdMinValue, "minValue", 1);
4715 create_builtin_fn_with_arg_count(g, BuiltinFnIdMemberCount, "member_count", 1);4715 create_builtin_fn_with_arg_count(g, BuiltinFnIdMemberCount, "memberCount", 1);
4716 create_builtin_fn_with_arg_count(g, BuiltinFnIdTypeof, "typeof", 1);4716 create_builtin_fn_with_arg_count(g, BuiltinFnIdTypeof, "typeOf", 1);
4717 create_builtin_fn_with_arg_count(g, BuiltinFnIdAddWithOverflow, "add_with_overflow", 4);4717 create_builtin_fn_with_arg_count(g, BuiltinFnIdAddWithOverflow, "addWithOverflow", 4);
4718 create_builtin_fn_with_arg_count(g, BuiltinFnIdSubWithOverflow, "sub_with_overflow", 4);4718 create_builtin_fn_with_arg_count(g, BuiltinFnIdSubWithOverflow, "subWithOverflow", 4);
4719 create_builtin_fn_with_arg_count(g, BuiltinFnIdMulWithOverflow, "mul_with_overflow", 4);4719 create_builtin_fn_with_arg_count(g, BuiltinFnIdMulWithOverflow, "mulWithOverflow", 4);
4720 create_builtin_fn_with_arg_count(g, BuiltinFnIdShlWithOverflow, "shl_with_overflow", 4);4720 create_builtin_fn_with_arg_count(g, BuiltinFnIdShlWithOverflow, "shlWithOverflow", 4);
4721 create_builtin_fn_with_arg_count(g, BuiltinFnIdCInclude, "c_include", 1);4721 create_builtin_fn_with_arg_count(g, BuiltinFnIdCInclude, "cInclude", 1);
4722 create_builtin_fn_with_arg_count(g, BuiltinFnIdCDefine, "c_define", 2);4722 create_builtin_fn_with_arg_count(g, BuiltinFnIdCDefine, "cDefine", 2);
4723 create_builtin_fn_with_arg_count(g, BuiltinFnIdCUndef, "c_undef", 1);4723 create_builtin_fn_with_arg_count(g, BuiltinFnIdCUndef, "cUndef", 1);
4724 create_builtin_fn_with_arg_count(g, BuiltinFnIdCompileVar, "compile_var", 1);4724 create_builtin_fn_with_arg_count(g, BuiltinFnIdCompileVar, "compileVar", 1);
4725 create_builtin_fn_with_arg_count(g, BuiltinFnIdConstEval, "const_eval", 1);4725 create_builtin_fn_with_arg_count(g, BuiltinFnIdConstEval, "constEval", 1);
4726 create_builtin_fn_with_arg_count(g, BuiltinFnIdCtz, "ctz", 2);4726 create_builtin_fn_with_arg_count(g, BuiltinFnIdCtz, "ctz", 2);
4727 create_builtin_fn_with_arg_count(g, BuiltinFnIdClz, "clz", 2);4727 create_builtin_fn_with_arg_count(g, BuiltinFnIdClz, "clz", 2);
4728 create_builtin_fn_with_arg_count(g, BuiltinFnIdImport, "import", 1);4728 create_builtin_fn_with_arg_count(g, BuiltinFnIdImport, "import", 1);
4729 create_builtin_fn_with_arg_count(g, BuiltinFnIdCImport, "c_import", 1);4729 create_builtin_fn_with_arg_count(g, BuiltinFnIdCImport, "cImport", 1);
4730 create_builtin_fn_with_arg_count(g, BuiltinFnIdErrName, "err_name", 1);4730 create_builtin_fn_with_arg_count(g, BuiltinFnIdErrName, "errName", 1);
4731 create_builtin_fn_with_arg_count(g, BuiltinFnIdEmbedFile, "embed_file", 1);4731 create_builtin_fn_with_arg_count(g, BuiltinFnIdEmbedFile, "embedFile", 1);
4732 create_builtin_fn_with_arg_count(g, BuiltinFnIdCmpExchange, "cmpxchg", 5);4732 create_builtin_fn_with_arg_count(g, BuiltinFnIdCmpExchange, "cmpxchg", 5);
4733 create_builtin_fn_with_arg_count(g, BuiltinFnIdFence, "fence", 1);4733 create_builtin_fn_with_arg_count(g, BuiltinFnIdFence, "fence", 1);
4734 create_builtin_fn_with_arg_count(g, BuiltinFnIdDivExact, "div_exact", 2);4734 create_builtin_fn_with_arg_count(g, BuiltinFnIdDivExact, "divExact", 2);
4735 create_builtin_fn_with_arg_count(g, BuiltinFnIdTruncate, "truncate", 2);4735 create_builtin_fn_with_arg_count(g, BuiltinFnIdTruncate, "truncate", 2);
4736 create_builtin_fn_with_arg_count(g, BuiltinFnIdCompileErr, "compile_err", 1);4736 create_builtin_fn_with_arg_count(g, BuiltinFnIdCompileErr, "compileErr", 1);
4737 create_builtin_fn_with_arg_count(g, BuiltinFnIdIntType, "int_type", 2);4737 create_builtin_fn_with_arg_count(g, BuiltinFnIdIntType, "intType", 2);
4738}4738}
47394739
4740static void init(CodeGen *g, Buf *source_path) {4740static void init(CodeGen *g, Buf *source_path) {
std/bootstrap.zig+8-8
...@@ -4,7 +4,7 @@ const root = @import("@root");...@@ -4,7 +4,7 @@ const root = @import("@root");
4const linux = @import("linux.zig");4const linux = @import("linux.zig");
5const cstr = @import("cstr.zig");5const cstr = @import("cstr.zig");
66
7const want_start_symbol = switch(@compile_var("os")) {7const want_start_symbol = switch(@compileVar("os")) {
8 linux => true,8 linux => true,
9 else => false,9 else => false,
10};10};
...@@ -16,7 +16,7 @@ var argv: &&u8 = undefined;...@@ -16,7 +16,7 @@ var argv: &&u8 = undefined;
16#attribute("naked")16#attribute("naked")
17#condition(want_start_symbol)17#condition(want_start_symbol)
18export fn _start() -> unreachable {18export fn _start() -> unreachable {
19 switch (@compile_var("arch")) {19 switch (@compileVar("arch")) {
20 x86_64 => {20 x86_64 => {
21 argc = asm("mov (%%rsp), %[argc]": [argc] "=r" (-> usize));21 argc = asm("mov (%%rsp), %[argc]": [argc] "=r" (-> usize));
22 argv = asm("lea 0x8(%%rsp), %[argv]": [argv] "=r" (-> &&u8));22 argv = asm("lea 0x8(%%rsp), %[argv]": [argv] "=r" (-> &&u8));
...@@ -25,12 +25,12 @@ export fn _start() -> unreachable {...@@ -25,12 +25,12 @@ export fn _start() -> unreachable {
25 argc = asm("mov (%%esp), %[argc]": [argc] "=r" (-> usize));25 argc = asm("mov (%%esp), %[argc]": [argc] "=r" (-> usize));
26 argv = asm("lea 0x4(%%esp), %[argv]": [argv] "=r" (-> &&u8));26 argv = asm("lea 0x4(%%esp), %[argv]": [argv] "=r" (-> &&u8));
27 },27 },
28 else => @compile_err("unsupported arch"),28 else => @compileErr("unsupported arch"),
29 }29 }
30 call_main_and_exit()30 callMainAndExit()
31}31}
3232
33fn call_main() -> %void {33fn callMain() -> %void {
34 var args: [argc][]u8 = undefined;34 var args: [argc][]u8 = undefined;
35 for (args) |arg, i| {35 for (args) |arg, i| {
36 const ptr = argv[i];36 const ptr = argv[i];
...@@ -39,8 +39,8 @@ fn call_main() -> %void {...@@ -39,8 +39,8 @@ fn call_main() -> %void {
39 return root.main(args);39 return root.main(args);
40}40}
4141
42fn call_main_and_exit() -> unreachable {42fn callMainAndExit() -> unreachable {
43 call_main() %% linux.exit(1);43 callMain() %% linux.exit(1);
44 linux.exit(0);44 linux.exit(0);
45}45}
4646
...@@ -48,6 +48,6 @@ fn call_main_and_exit() -> unreachable {...@@ -48,6 +48,6 @@ fn call_main_and_exit() -> unreachable {
48export fn main(c_argc: i32, c_argv: &&u8) -> i32 {48export fn main(c_argc: i32, c_argv: &&u8) -> i32 {
49 argc = usize(c_argc);49 argc = usize(c_argc);
50 argv = c_argv;50 argv = c_argv;
51 call_main() %% return 1;51 callMain() %% return 1;
52 return 0;52 return 0;
53}53}
std/compiler_rt.zig+5-5
...@@ -5,7 +5,7 @@ const si_int = c_int;...@@ -5,7 +5,7 @@ const si_int = c_int;
5const su_int = c_uint;5const su_int = c_uint;
66
7const udwords = [2]su_int;7const udwords = [2]su_int;
8const low = if (@compile_var("is_big_endian")) 1 else 0;8const low = if (@compileVar("is_big_endian")) 1 else 0;
9const high = 1 - low;9const high = 1 - low;
1010
11#debug_safety(false)11#debug_safety(false)
...@@ -20,8 +20,8 @@ fn du_int_to_udwords(x: du_int) -> udwords {...@@ -20,8 +20,8 @@ fn du_int_to_udwords(x: du_int) -> udwords {
2020
21#debug_safety(false)21#debug_safety(false)
22export fn __udivmoddi4(a: du_int, b: du_int, maybe_rem: ?&du_int) -> du_int {22export fn __udivmoddi4(a: du_int, b: du_int, maybe_rem: ?&du_int) -> du_int {
23 const n_uword_bits = @sizeof(su_int) * CHAR_BIT;23 const n_uword_bits = @sizeOf(su_int) * CHAR_BIT;
24 const n_udword_bits = @sizeof(du_int) * CHAR_BIT;24 const n_udword_bits = @sizeOf(du_int) * CHAR_BIT;
25 var n = du_int_to_udwords(a);25 var n = du_int_to_udwords(a);
26 var d = du_int_to_udwords(b);26 var d = du_int_to_udwords(b);
27 var q: udwords = undefined;27 var q: udwords = undefined;
...@@ -79,7 +79,7 @@ export fn __udivmoddi4(a: du_int, b: du_int, maybe_rem: ?&du_int) -> du_int {...@@ -79,7 +79,7 @@ export fn __udivmoddi4(a: du_int, b: du_int, maybe_rem: ?&du_int) -> du_int {
79 r[high] = n[high] & (d[high] - 1);79 r[high] = n[high] & (d[high] - 1);
80 *rem = *(&du_int)(&r[0]);80 *rem = *(&du_int)(&r[0]);
81 }81 }
82 return n[high] >> @ctz(@typeof(d[high]), d[high]);82 return n[high] >> @ctz(@typeOf(d[high]), d[high]);
83 }83 }
84 // K K84 // K K
85 // ---85 // ---
...@@ -114,7 +114,7 @@ export fn __udivmoddi4(a: du_int, b: du_int, maybe_rem: ?&du_int) -> du_int {...@@ -114,7 +114,7 @@ export fn __udivmoddi4(a: du_int, b: du_int, maybe_rem: ?&du_int) -> du_int {
114 if (d[low] == 1) {114 if (d[low] == 1) {
115 return *(&du_int)(&n[0]);115 return *(&du_int)(&n[0]);
116 }116 }
117 sr = @ctz(@typeof(d[low]), d[low]);117 sr = @ctz(@typeOf(d[low]), d[low]);
118 q[high] = n[high] >> sr;118 q[high] = n[high] >> sr;
119 q[low] = (n[high] << (n_uword_bits - sr)) | (n[low] >> sr);119 q[low] = (n[high] << (n_uword_bits - sr)) | (n[low] >> sr);
120 return *(&du_int)(&q[0]);120 return *(&du_int)(&q[0]);
std/cstr.zig+34-34
...@@ -24,11 +24,11 @@ pub fn cmp(a: &const u8, b: &const u8) -> i32 {...@@ -24,11 +24,11 @@ pub fn cmp(a: &const u8, b: &const u8) -> i32 {
24 return a[index] - b[index];24 return a[index] - b[index];
25}25}
2626
27pub fn to_slice_const(str: &const u8) -> []const u8 {27pub fn toSliceConst(str: &const u8) -> []const u8 {
28 return str[0...strlen(str)];28 return str[0...strlen(str)];
29}29}
3030
31pub fn to_slice(str: &u8) -> []u8 {31pub fn toSlice(str: &u8) -> []u8 {
32 return str[0...strlen(str)];32 return str[0...strlen(str)];
33}33}
3434
...@@ -46,25 +46,25 @@ pub struct CBuf {...@@ -46,25 +46,25 @@ pub struct CBuf {
46 }46 }
4747
48 /// Must deinitialize with deinit.48 /// Must deinitialize with deinit.
49 pub fn init_from_mem(self: &CBuf, allocator: &Allocator, m: []const u8) -> %void {49 pub fn initFromMem(self: &CBuf, allocator: &Allocator, m: []const u8) -> %void {
50 self.init(allocator);50 self.init(allocator);
51 %return self.resize(m.len);51 %return self.resize(m.len);
52 mem.copy(u8, self.list.items, m);52 mem.copy(u8, self.list.items, m);
53 }53 }
5454
55 /// Must deinitialize with deinit.55 /// Must deinitialize with deinit.
56 pub fn init_from_cstr(self: &CBuf, allocator: &Allocator, s: &const u8) -> %void {56 pub fn initFromCStr(self: &CBuf, allocator: &Allocator, s: &const u8) -> %void {
57 self.init_from_mem(allocator, s[0...strlen(s)])57 self.initFromMem(allocator, s[0...strlen(s)])
58 }58 }
5959
60 /// Must deinitialize with deinit.60 /// Must deinitialize with deinit.
61 pub fn init_from_cbuf(self: &CBuf, cbuf: &const CBuf) -> %void {61 pub fn initFromCBuf(self: &CBuf, cbuf: &const CBuf) -> %void {
62 self.init_from_mem(cbuf.list.allocator, cbuf.list.items[0...cbuf.len()])62 self.initFromMem(cbuf.list.allocator, cbuf.list.items[0...cbuf.len()])
63 }63 }
6464
65 /// Must deinitialize with deinit.65 /// Must deinitialize with deinit.
66 pub fn init_from_slice(self: &CBuf, other: &const CBuf, start: usize, end: usize) -> %void {66 pub fn initFromSlice(self: &CBuf, other: &const CBuf, start: usize, end: usize) -> %void {
67 self.init_from_mem(other.list.allocator, other.list.items[start...end])67 self.initFromMem(other.list.allocator, other.list.items[start...end])
68 }68 }
6969
70 pub fn deinit(self: &CBuf) {70 pub fn deinit(self: &CBuf) {
...@@ -80,66 +80,66 @@ pub struct CBuf {...@@ -80,66 +80,66 @@ pub struct CBuf {
80 return self.list.len - 1;80 return self.list.len - 1;
81 }81 }
8282
83 pub fn append_mem(self: &CBuf, m: []const u8) -> %void {83 pub fn appendMem(self: &CBuf, m: []const u8) -> %void {
84 const old_len = self.len();84 const old_len = self.len();
85 %return self.resize(old_len + m.len);85 %return self.resize(old_len + m.len);
86 mem.copy(u8, self.list.items[old_len...], m);86 mem.copy(u8, self.list.items[old_len...], m);
87 }87 }
8888
89 pub fn append_cstr(self: &CBuf, s: &const u8) -> %void {89 pub fn appendCStr(self: &CBuf, s: &const u8) -> %void {
90 self.append_mem(s[0...strlen(s)])90 self.appendMem(s[0...strlen(s)])
91 }91 }
9292
93 pub fn append_char(self: &CBuf, c: u8) -> %void {93 pub fn appendChar(self: &CBuf, c: u8) -> %void {
94 %return self.resize(self.len() + 1);94 %return self.resize(self.len() + 1);
95 self.list.items[self.len() - 1] = c;95 self.list.items[self.len() - 1] = c;
96 }96 }
9797
98 pub fn eql_mem(self: &const CBuf, m: []const u8) -> bool {98 pub fn eqlMem(self: &const CBuf, m: []const u8) -> bool {
99 if (self.len() != m.len) return false;99 if (self.len() != m.len) return false;
100 return mem.cmp(u8, self.list.items[0...m.len], m) == mem.Cmp.Equal;100 return mem.cmp(u8, self.list.items[0...m.len], m) == mem.Cmp.Equal;
101 }101 }
102102
103 pub fn eql_cstr(self: &const CBuf, s: &const u8) -> bool {103 pub fn eqlCStr(self: &const CBuf, s: &const u8) -> bool {
104 self.eql_mem(s[0...strlen(s)])104 self.eqlMem(s[0...strlen(s)])
105 }105 }
106106
107 pub fn eql_cbuf(self: &const CBuf, other: &const CBuf) -> bool {107 pub fn eqlCBuf(self: &const CBuf, other: &const CBuf) -> bool {
108 self.eql_mem(other.list.items[0...other.len()])108 self.eqlMem(other.list.items[0...other.len()])
109 }109 }
110110
111 pub fn starts_with_mem(self: &const CBuf, m: []const u8) -> bool {111 pub fn startsWithMem(self: &const CBuf, m: []const u8) -> bool {
112 if (self.len() < m.len) return false;112 if (self.len() < m.len) return false;
113 return mem.cmp(u8, self.list.items[0...m.len], m) == mem.Cmp.Equal;113 return mem.cmp(u8, self.list.items[0...m.len], m) == mem.Cmp.Equal;
114 }114 }
115115
116 pub fn starts_with_cbuf(self: &const CBuf, other: &const CBuf) -> bool {116 pub fn startsWithCBuf(self: &const CBuf, other: &const CBuf) -> bool {
117 self.starts_with_mem(other.list.items[0...other.len()])117 self.startsWithMem(other.list.items[0...other.len()])
118 }118 }
119119
120 pub fn starts_with_cstr(self: &const CBuf, s: &const u8) -> bool {120 pub fn startsWithCStr(self: &const CBuf, s: &const u8) -> bool {
121 self.starts_with_mem(s[0...strlen(s)])121 self.startsWithMem(s[0...strlen(s)])
122 }122 }
123}123}
124124
125#attribute("test")125#attribute("test")
126fn test_simple_cbuf() {126fn testSimpleCBuf() {
127 var buf: CBuf = undefined;127 var buf: CBuf = undefined;
128 buf.init(&debug.global_allocator);128 buf.init(&debug.global_allocator);
129 assert(buf.len() == 0);129 assert(buf.len() == 0);
130 %%buf.append_cstr(c"hello");130 %%buf.appendCStr(c"hello");
131 %%buf.append_char(' ');131 %%buf.appendChar(' ');
132 %%buf.append_mem("world");132 %%buf.appendMem("world");
133 assert(buf.eql_cstr(c"hello world"));133 assert(buf.eqlCStr(c"hello world"));
134 assert(buf.eql_mem("hello world"));134 assert(buf.eqlMem("hello world"));
135135
136 var buf2: CBuf = undefined;136 var buf2: CBuf = undefined;
137 %%buf2.init_from_cbuf(&buf);137 %%buf2.initFromCBuf(&buf);
138 assert(buf.eql_cbuf(&buf2));138 assert(buf.eqlCBuf(&buf2));
139139
140 assert(buf.starts_with_mem("hell"));140 assert(buf.startsWithMem("hell"));
141 assert(buf.starts_with_cstr(c"hell"));141 assert(buf.startsWithCStr(c"hell"));
142142
143 %%buf2.resize(4);143 %%buf2.resize(4);
144 assert(buf.starts_with_cbuf(&buf2));144 assert(buf.startsWithCBuf(&buf2));
145}145}
std/debug.zig+5-5
...@@ -6,10 +6,10 @@ pub fn assert(b: bool) {...@@ -6,10 +6,10 @@ pub fn assert(b: bool) {
6}6}
77
8pub fn printStackTrace() {8pub fn printStackTrace() {
9 var maybe_fp: ?&const u8 = @frame_address();9 var maybe_fp: ?&const u8 = @frameAddress();
10 while (true) {10 while (true) {
11 const fp = maybe_fp ?? break;11 const fp = maybe_fp ?? break;
12 const return_address = *(&const usize)(usize(fp) + @sizeof(usize));12 const return_address = *(&const usize)(usize(fp) + @sizeOf(usize));
13 %%io.stderr.print_u64(return_address);13 %%io.stderr.print_u64(return_address);
14 %%io.stderr.printf("\n");14 %%io.stderr.printf("\n");
15 maybe_fp = *(&const ?&const u8)(fp);15 maybe_fp = *(&const ?&const u8)(fp);
...@@ -17,9 +17,9 @@ pub fn printStackTrace() {...@@ -17,9 +17,9 @@ pub fn printStackTrace() {
17}17}
1818
19pub var global_allocator = Allocator {19pub var global_allocator = Allocator {
20 .alloc_fn = globalAlloc,20 .allocFn = globalAlloc,
21 .realloc_fn = globalRealloc,21 .reallocFn = globalRealloc,
22 .free_fn = globalFree,22 .freeFn = globalFree,
23 .context = null,23 .context = null,
24};24};
2525
std/hash_map.zig+22-22
...@@ -4,27 +4,27 @@ const math = @import("math.zig");...@@ -4,27 +4,27 @@ const math = @import("math.zig");
4const mem = @import("mem.zig");4const mem = @import("mem.zig");
5const Allocator = mem.Allocator;5const Allocator = mem.Allocator;
66
7const want_modification_safety = !@compile_var("is_release");7const want_modification_safety = !@compileVar("is_release");
8const debug_u32 = if (want_modification_safety) u32 else void;8const debug_u32 = if (want_modification_safety) u32 else void;
99
10pub fn HashMap(inline K: type, inline V: type, inline hash: fn(key: K)->u32,10pub fn HashMap(inline K: type, inline V: type, inline hash: fn(key: K)->u32,
11 inline eql: fn(a: K, b: K)->bool) -> type11 inline eql: fn(a: K, b: K)->bool) -> type
12{12{
13 SmallHashMap(K, V, hash, eql, @sizeof(usize))13 SmallHashMap(K, V, hash, eql, @sizeOf(usize))
14}14}
1515
16pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b: K)->bool, STATIC_SIZE: usize) {16pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b: K)->bool, static_size: usize) {
17 entries: []Entry,17 entries: []Entry,
18 size: usize,18 size: usize,
19 max_distance_from_start_index: usize,19 max_distance_from_start_index: usize,
20 allocator: &Allocator,20 allocator: &Allocator,
21 // if the hash map is small enough, we use linear search through these21 // if the hash map is small enough, we use linear search through these
22 // entries instead of allocating memory22 // entries instead of allocating memory
23 prealloc_entries: [STATIC_SIZE]Entry,23 prealloc_entries: [static_size]Entry,
24 // this is used to detect bugs where a hashtable is edited while an iterator is running.24 // this is used to detect bugs where a hashtable is edited while an iterator is running.
25 modification_count: debug_u32,25 modification_count: debug_u32,
2626
27 const Self = SmallHashMap(K, V, hash, eql, STATIC_SIZE);27 const Self = SmallHashMap(K, V, hash, eql, static_size);
2828
29 pub struct Entry {29 pub struct Entry {
30 used: bool,30 used: bool,
...@@ -80,11 +80,11 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b...@@ -80,11 +80,11 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b
80 }80 }
81 hm.size = 0;81 hm.size = 0;
82 hm.max_distance_from_start_index = 0;82 hm.max_distance_from_start_index = 0;
83 hm.increment_modification_count();83 hm.incrementModificationCount();
84 }84 }
8585
86 pub fn put(hm: &Self, key: K, value: V) -> %void {86 pub fn put(hm: &Self, key: K, value: V) -> %void {
87 hm.increment_modification_count();87 hm.incrementModificationCount();
8888
89 const resize = if (hm.entries.ptr == &hm.prealloc_entries[0]) {89 const resize = if (hm.entries.ptr == &hm.prealloc_entries[0]) {
90 // preallocated entries table is full90 // preallocated entries table is full
...@@ -95,11 +95,11 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b...@@ -95,11 +95,11 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b
95 };95 };
96 if (resize) {96 if (resize) {
97 const old_entries = hm.entries;97 const old_entries = hm.entries;
98 %return hm.init_capacity(hm.entries.len * 2);98 %return hm.initCapacity(hm.entries.len * 2);
99 // dump all of the old elements into the new table99 // dump all of the old elements into the new table
100 for (old_entries) |*old_entry| {100 for (old_entries) |*old_entry| {
101 if (old_entry.used) {101 if (old_entry.used) {
102 hm.internal_put(old_entry.key, old_entry.value);102 hm.internalPut(old_entry.key, old_entry.value);
103 }103 }
104 }104 }
105 if (old_entries.ptr != &hm.prealloc_entries[0]) {105 if (old_entries.ptr != &hm.prealloc_entries[0]) {
...@@ -107,16 +107,16 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b...@@ -107,16 +107,16 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b
107 }107 }
108 }108 }
109109
110 hm.internal_put(key, value);110 hm.internalPut(key, value);
111 }111 }
112112
113 pub fn get(hm: &Self, key: K) -> ?&Entry {113 pub fn get(hm: &Self, key: K) -> ?&Entry {
114 return hm.internal_get(key);114 return hm.internalGet(key);
115 }115 }
116116
117 pub fn remove(hm: &Self, key: K) {117 pub fn remove(hm: &Self, key: K) {
118 hm.increment_modification_count();118 hm.incrementModificationCount();
119 const start_index = hm.key_to_index(key);119 const start_index = hm.keyToIndex(key);
120 {var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index; roll_over += 1) {120 {var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index; roll_over += 1) {
121 const index = (start_index + roll_over) % hm.entries.len;121 const index = (start_index + roll_over) % hm.entries.len;
122 var entry = &hm.entries[index];122 var entry = &hm.entries[index];
...@@ -142,7 +142,7 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b...@@ -142,7 +142,7 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b
142 unreachable{} // key not found142 unreachable{} // key not found
143 }143 }
144144
145 pub fn entry_iterator(hm: &Self) -> Iterator {145 pub fn entryIterator(hm: &Self) -> Iterator {
146 return Iterator {146 return Iterator {
147 .hm = hm,147 .hm = hm,
148 .count = 0,148 .count = 0,
...@@ -151,7 +151,7 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b...@@ -151,7 +151,7 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b
151 };151 };
152 }152 }
153153
154 fn init_capacity(hm: &Self, capacity: usize) -> %void {154 fn initCapacity(hm: &Self, capacity: usize) -> %void {
155 hm.entries = %return hm.allocator.alloc(Entry, capacity);155 hm.entries = %return hm.allocator.alloc(Entry, capacity);
156 hm.size = 0;156 hm.size = 0;
157 hm.max_distance_from_start_index = 0;157 hm.max_distance_from_start_index = 0;
...@@ -160,16 +160,16 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b...@@ -160,16 +160,16 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b
160 }160 }
161 }161 }
162162
163 fn increment_modification_count(hm: &Self) {163 fn incrementModificationCount(hm: &Self) {
164 if (want_modification_safety) {164 if (want_modification_safety) {
165 hm.modification_count +%= 1;165 hm.modification_count +%= 1;
166 }166 }
167 }167 }
168168
169 fn internal_put(hm: &Self, orig_key: K, orig_value: V) {169 fn internalPut(hm: &Self, orig_key: K, orig_value: V) {
170 var key = orig_key;170 var key = orig_key;
171 var value = orig_value;171 var value = orig_value;
172 const start_index = hm.key_to_index(key);172 const start_index = hm.keyToIndex(key);
173 var roll_over: usize = 0;173 var roll_over: usize = 0;
174 var distance_from_start_index: usize = 0;174 var distance_from_start_index: usize = 0;
175 while (roll_over < hm.entries.len; {roll_over += 1; distance_from_start_index += 1}) {175 while (roll_over < hm.entries.len; {roll_over += 1; distance_from_start_index += 1}) {
...@@ -214,8 +214,8 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b...@@ -214,8 +214,8 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b
214 unreachable{} // put into a full map214 unreachable{} // put into a full map
215 }215 }
216216
217 fn internal_get(hm: &Self, key: K) -> ?&Entry {217 fn internalGet(hm: &Self, key: K) -> ?&Entry {
218 const start_index = hm.key_to_index(key);218 const start_index = hm.keyToIndex(key);
219 {var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index; roll_over += 1) {219 {var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index; roll_over += 1) {
220 const index = (start_index + roll_over) % hm.entries.len;220 const index = (start_index + roll_over) % hm.entries.len;
221 const entry = &hm.entries[index];221 const entry = &hm.entries[index];
...@@ -226,13 +226,13 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b...@@ -226,13 +226,13 @@ pub struct SmallHashMap(K: type, V: type, hash: fn(key: K)->u32, eql: fn(a: K, b
226 return null;226 return null;
227 }227 }
228228
229 fn key_to_index(hm: &Self, key: K) -> usize {229 fn keyToIndex(hm: &Self, key: K) -> usize {
230 return usize(hash(key)) % hm.entries.len;230 return usize(hash(key)) % hm.entries.len;
231 }231 }
232}232}
233233
234#attribute("test")234#attribute("test")
235fn basic_hash_map_test() {235fn basicHashMapTest() {
236 var map: HashMap(i32, i32, hash_i32, eql_i32) = undefined;236 var map: HashMap(i32, i32, hash_i32, eql_i32) = undefined;
237 map.init(&debug.global_allocator);237 map.init(&debug.global_allocator);
238 defer map.deinit();238 defer map.deinit();
std/index.zig+1-1
...@@ -9,7 +9,7 @@ pub const list = @import("list.zig");...@@ -9,7 +9,7 @@ pub const list = @import("list.zig");
9pub const hash_map = @import("hash_map.zig");9pub const hash_map = @import("hash_map.zig");
10pub const mem = @import("mem.zig");10pub const mem = @import("mem.zig");
11pub const debug = @import("debug.zig");11pub const debug = @import("debug.zig");
12pub const linux = switch(@compile_var("os")) {12pub const linux = switch(@compileVar("os")) {
13 linux => @import("linux.zig"),13 linux => @import("linux.zig"),
14 else => null_import,14 else => null_import,
15};15};
std/io.zig+21-29
...@@ -63,7 +63,7 @@ pub struct OutStream {...@@ -63,7 +63,7 @@ pub struct OutStream {
63 buffer: [buffer_size]u8,63 buffer: [buffer_size]u8,
64 index: usize,64 index: usize,
6565
66 pub fn write_byte(os: &OutStream, b: u8) -> %void {66 pub fn writeByte(os: &OutStream, b: u8) -> %void {
67 if (os.buffer.len == os.index) %return os.flush();67 if (os.buffer.len == os.index) %return os.flush();
68 os.buffer[os.index] = b;68 os.buffer[os.index] = b;
69 os.index += 1;69 os.index += 1;
...@@ -71,7 +71,7 @@ pub struct OutStream {...@@ -71,7 +71,7 @@ pub struct OutStream {
7171
72 pub fn write(os: &OutStream, bytes: []const u8) -> %usize {72 pub fn write(os: &OutStream, bytes: []const u8) -> %usize {
73 var src_bytes_left = bytes.len;73 var src_bytes_left = bytes.len;
74 var src_index: @typeof(bytes.len) = 0;74 var src_index: @typeOf(bytes.len) = 0;
75 const dest_space_left = os.buffer.len - os.index;75 const dest_space_left = os.buffer.len - os.index;
7676
77 while (src_bytes_left > 0) {77 while (src_bytes_left > 0) {
...@@ -98,7 +98,7 @@ pub struct OutStream {...@@ -98,7 +98,7 @@ pub struct OutStream {
98 if (os.index + max_u64_base10_digits >= os.buffer.len) {98 if (os.index + max_u64_base10_digits >= os.buffer.len) {
99 %return os.flush();99 %return os.flush();
100 }100 }
101 const amt_printed = buf_print_u64(os.buffer[os.index...], x);101 const amt_printed = bufPrintUnsigned(u64, os.buffer[os.index...], x);
102 os.index += amt_printed;102 os.index += amt_printed;
103103
104 return amt_printed;104 return amt_printed;
...@@ -108,7 +108,7 @@ pub struct OutStream {...@@ -108,7 +108,7 @@ pub struct OutStream {
108 if (os.index + max_u64_base10_digits >= os.buffer.len) {108 if (os.index + max_u64_base10_digits >= os.buffer.len) {
109 %return os.flush();109 %return os.flush();
110 }110 }
111 const amt_printed = buf_print_i64(os.buffer[os.index...], x);111 const amt_printed = bufPrintSigned(i64, os.buffer[os.index...], x);
112 os.index += amt_printed;112 os.index += amt_printed;
113113
114 return amt_printed;114 return amt_printed;
...@@ -116,7 +116,7 @@ pub struct OutStream {...@@ -116,7 +116,7 @@ pub struct OutStream {
116116
117 pub fn flush(os: &OutStream) -> %void {117 pub fn flush(os: &OutStream) -> %void {
118 const write_ret = linux.write(os.fd, &os.buffer[0], os.index);118 const write_ret = linux.write(os.fd, &os.buffer[0], os.index);
119 const write_err = linux.get_errno(write_ret);119 const write_err = linux.getErrno(write_ret);
120 if (write_err > 0) {120 if (write_err > 0) {
121 return switch (write_err) {121 return switch (write_err) {
122 errno.EINVAL => unreachable{},122 errno.EINVAL => unreachable{},
...@@ -135,7 +135,7 @@ pub struct OutStream {...@@ -135,7 +135,7 @@ pub struct OutStream {
135135
136 pub fn close(os: &OutStream) -> %void {136 pub fn close(os: &OutStream) -> %void {
137 const close_ret = linux.close(os.fd);137 const close_ret = linux.close(os.fd);
138 const close_err = linux.get_errno(close_ret);138 const close_err = linux.getErrno(close_ret);
139 if (close_err > 0) {139 if (close_err > 0) {
140 return switch (close_err) {140 return switch (close_err) {
141 errno.EIO => error.Io,141 errno.EIO => error.Io,
...@@ -152,7 +152,7 @@ pub struct InStream {...@@ -152,7 +152,7 @@ pub struct InStream {
152152
153 pub fn open(path: []u8) -> %InStream {153 pub fn open(path: []u8) -> %InStream {
154 const fd = linux.open(path, linux.O_LARGEFILE|linux.O_RDONLY, 0);154 const fd = linux.open(path, linux.O_LARGEFILE|linux.O_RDONLY, 0);
155 const fd_err = linux.get_errno(fd);155 const fd_err = linux.getErrno(fd);
156 if (fd_err > 0) {156 if (fd_err > 0) {
157 return switch (fd_err) {157 return switch (fd_err) {
158 errno.EFAULT => unreachable{},158 errno.EFAULT => unreachable{},
...@@ -180,7 +180,7 @@ pub struct InStream {...@@ -180,7 +180,7 @@ pub struct InStream {
180180
181 pub fn read(is: &InStream, buf: []u8) -> %usize {181 pub fn read(is: &InStream, buf: []u8) -> %usize {
182 const amt_read = linux.read(is.fd, &buf[0], buf.len);182 const amt_read = linux.read(is.fd, &buf[0], buf.len);
183 const read_err = linux.get_errno(amt_read);183 const read_err = linux.getErrno(amt_read);
184 if (read_err > 0) {184 if (read_err > 0) {
185 return switch (read_err) {185 return switch (read_err) {
186 errno.EINVAL => unreachable{},186 errno.EINVAL => unreachable{},
...@@ -196,7 +196,7 @@ pub struct InStream {...@@ -196,7 +196,7 @@ pub struct InStream {
196196
197 pub fn close(is: &InStream) -> %void {197 pub fn close(is: &InStream) -> %void {
198 const close_ret = linux.close(is.fd);198 const close_ret = linux.close(is.fd);
199 const close_err = linux.get_errno(close_ret);199 const close_err = linux.getErrno(close_ret);
200 if (close_err > 0) {200 if (close_err > 0) {
201 return switch (close_err) {201 return switch (close_err) {
202 errno.EIO => error.Io,202 errno.EIO => error.Io,
...@@ -208,20 +208,20 @@ pub struct InStream {...@@ -208,20 +208,20 @@ pub struct InStream {
208 }208 }
209}209}
210210
211pub fn parse_unsigned(inline T: type, buf: []u8, radix: u8) -> %T {211pub fn parseUnsigned(inline T: type, buf: []u8, radix: u8) -> %T {
212 var x: T = 0;212 var x: T = 0;
213213
214 for (buf) |c| {214 for (buf) |c| {
215 const digit = %return char_to_digit(c, radix);215 const digit = %return charToDigit(c, radix);
216 x = %return math.mul_overflow(T, x, radix);216 x = %return math.mulOverflow(T, x, radix);
217 x = %return math.add_overflow(T, x, digit);217 x = %return math.addOverflow(T, x, digit);
218 }218 }
219219
220 return x;220 return x;
221}221}
222222
223pub error InvalidChar;223pub error InvalidChar;
224fn char_to_digit(c: u8, radix: u8) -> %u8 {224fn charToDigit(c: u8, radix: u8) -> %u8 {
225 const value = if ('0' <= c && c <= '9') {225 const value = if ('0' <= c && c <= '9') {
226 c - '0'226 c - '0'
227 } else if ('A' <= c && c <= 'Z') {227 } else if ('A' <= c && c <= 'Z') {
...@@ -234,21 +234,17 @@ fn char_to_digit(c: u8, radix: u8) -> %u8 {...@@ -234,21 +234,17 @@ fn char_to_digit(c: u8, radix: u8) -> %u8 {
234 return if (value >= radix) error.InvalidChar else value;234 return if (value >= radix) error.InvalidChar else value;
235}235}
236236
237pub fn buf_print_signed(inline T: type, out_buf: []u8, x: T) -> usize {237pub fn bufPrintSigned(inline T: type, out_buf: []u8, x: T) -> usize {
238 const uint = @int_type(false, T.bit_count);238 const uint = @intType(false, T.bit_count);
239 if (x < 0) {239 if (x < 0) {
240 out_buf[0] = '-';240 out_buf[0] = '-';
241 return 1 + buf_print_unsigned(uint, out_buf[1...], uint(-(x + 1)) + 1);241 return 1 + bufPrintUnsigned(uint, out_buf[1...], uint(-(x + 1)) + 1);
242 } else {242 } else {
243 return buf_print_unsigned(uint, out_buf, uint(x));243 return bufPrintUnsigned(uint, out_buf, uint(x));
244 }244 }
245}245}
246246
247pub fn buf_print_i64(out_buf: []u8, x: i64) -> usize {247pub fn bufPrintUnsigned(inline T: type, out_buf: []u8, x: T) -> usize {
248 buf_print_signed(i64, out_buf, x)
249}
250
251pub fn buf_print_unsigned(inline T: type, out_buf: []u8, x: T) -> usize {
252 var buf: [max_u64_base10_digits]u8 = undefined;248 var buf: [max_u64_base10_digits]u8 = undefined;
253 var a = x;249 var a = x;
254 var index: usize = buf.len;250 var index: usize = buf.len;
...@@ -269,13 +265,9 @@ pub fn buf_print_unsigned(inline T: type, out_buf: []u8, x: T) -> usize {...@@ -269,13 +265,9 @@ pub fn buf_print_unsigned(inline T: type, out_buf: []u8, x: T) -> usize {
269 return len;265 return len;
270}266}
271267
272pub fn buf_print_u64(out_buf: []u8, x: u64) -> usize {
273 buf_print_unsigned(u64, out_buf, x)
274}
275
276#attribute("test")268#attribute("test")
277fn parse_u64_digit_too_big() {269fn parseU64DigitTooBig() {
278 parse_unsigned(u64, "123a", 10) %% |err| {270 parseUnsigned(u64, "123a", 10) %% |err| {
279 if (err == error.InvalidChar) return;271 if (err == error.InvalidChar) return;
280 unreachable{};272 unreachable{};
281 };273 };
std/linux.zig+9-9
...@@ -1,4 +1,4 @@...@@ -1,4 +1,4 @@
1const arch = switch (@compile_var("arch")) {1const arch = switch (@compileVar("arch")) {
2 x86_64 => @import("linux_x86_64.zig"),2 x86_64 => @import("linux_x86_64.zig"),
3 i386 => @import("linux_i386.zig"),3 i386 => @import("linux_i386.zig"),
4 else => @compile_err("unsupported arch"),4 else => @compile_err("unsupported arch"),
...@@ -221,7 +221,7 @@ pub const AF_VSOCK = PF_VSOCK;...@@ -221,7 +221,7 @@ pub const AF_VSOCK = PF_VSOCK;
221pub const AF_MAX = PF_MAX;221pub const AF_MAX = PF_MAX;
222222
223/// Get the errno from a syscall return value, or 0 for no error.223/// Get the errno from a syscall return value, or 0 for no error.
224pub fn get_errno(r: usize) -> usize {224pub fn getErrno(r: usize) -> usize {
225 const signed_r = *(&isize)(&r);225 const signed_r = *(&isize)(&r);
226 if (signed_r > -4096 && signed_r < 0) usize(-signed_r) else 0226 if (signed_r > -4096 && signed_r < 0) usize(-signed_r) else 0
227}227}
...@@ -291,22 +291,22 @@ const app_mask = []u8 { 0xff, 0xff, 0xff, 0xfc, 0x7f, 0xff, 0xff, 0xff, };...@@ -291,22 +291,22 @@ const app_mask = []u8 { 0xff, 0xff, 0xff, 0xfc, 0x7f, 0xff, 0xff, 0xff, };
291291
292pub fn raise(sig: i32) -> i32 {292pub fn raise(sig: i32) -> i32 {
293 var set: sigset_t = undefined;293 var set: sigset_t = undefined;
294 block_app_signals(&set);294 blockAppSignals(&set);
295 const tid = i32(arch.syscall0(arch.SYS_gettid));295 const tid = i32(arch.syscall0(arch.SYS_gettid));
296 const ret = i32(arch.syscall2(arch.SYS_tkill, usize(tid), usize(sig)));296 const ret = i32(arch.syscall2(arch.SYS_tkill, usize(tid), usize(sig)));
297 restore_signals(&set);297 restoreSignals(&set);
298 return ret;298 return ret;
299}299}
300300
301fn block_all_signals(set: &sigset_t) {301fn blockAllSignals(set: &sigset_t) {
302 arch.syscall4(arch.SYS_rt_sigprocmask, SIG_BLOCK, usize(&all_mask), usize(set), NSIG/8);302 arch.syscall4(arch.SYS_rt_sigprocmask, SIG_BLOCK, usize(&all_mask), usize(set), NSIG/8);
303}303}
304304
305fn block_app_signals(set: &sigset_t) {305fn blockAppSignals(set: &sigset_t) {
306 arch.syscall4(arch.SYS_rt_sigprocmask, SIG_BLOCK, usize(&app_mask), usize(set), NSIG/8);306 arch.syscall4(arch.SYS_rt_sigprocmask, SIG_BLOCK, usize(&app_mask), usize(set), NSIG/8);
307}307}
308308
309fn restore_signals(set: &sigset_t) {309fn restoreSignals(set: &sigset_t) {
310 arch.syscall4(arch.SYS_rt_sigprocmask, SIG_SETMASK, usize(set), 0, NSIG/8);310 arch.syscall4(arch.SYS_rt_sigprocmask, SIG_SETMASK, usize(set), 0, NSIG/8);
311}311}
312312
...@@ -442,7 +442,7 @@ pub fn accept4(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t, flags:...@@ -442,7 +442,7 @@ pub fn accept4(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t, flags:
442// }442// }
443// 443//
444// const socket_ret = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);444// const socket_ret = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
445// const socket_err = get_errno(socket_ret);445// const socket_err = getErrno(socket_ret);
446// if (socket_err > 0) {446// if (socket_err > 0) {
447// return error.SystemResources;447// return error.SystemResources;
448// }448// }
...@@ -451,7 +451,7 @@ pub fn accept4(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t, flags:...@@ -451,7 +451,7 @@ pub fn accept4(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t, flags:
451// ifr.ifr_name[name.len] = 0;451// ifr.ifr_name[name.len] = 0;
452// const ioctl_ret = ioctl(socket_fd, SIOCGIFINDEX, &ifr);452// const ioctl_ret = ioctl(socket_fd, SIOCGIFINDEX, &ifr);
453// close(socket_fd);453// close(socket_fd);
454// const ioctl_err = get_errno(ioctl_ret);454// const ioctl_err = getErrno(ioctl_ret);
455// if (ioctl_err > 0) {455// if (ioctl_err > 0) {
456// return error.Io;456// return error.Io;
457// }457// }
std/list.zig+10-10
...@@ -4,17 +4,17 @@ const mem = @import("mem.zig");...@@ -4,17 +4,17 @@ const mem = @import("mem.zig");
4const Allocator = mem.Allocator;4const Allocator = mem.Allocator;
55
6pub fn List(inline T: type) -> type {6pub fn List(inline T: type) -> type {
7 SmallList(T, @sizeof(usize))7 SmallList(T, @sizeOf(usize))
8}8}
99
10// TODO: make sure that setting STATIC_SIZE to 0 codegens to the same code10// TODO: make sure that setting static_size to 0 codegens to the same code
11// as if this were programmed without STATIC_SIZE at all.11// as if this were programmed without static_size at all.
12pub struct SmallList(T: type, STATIC_SIZE: usize) {12pub struct SmallList(T: type, static_size: usize) {
13 const Self = SmallList(T, STATIC_SIZE);13 const Self = SmallList(T, static_size);
1414
15 items: []T,15 items: []T,
16 len: usize,16 len: usize,
17 prealloc_items: [STATIC_SIZE]T,17 prealloc_items: [static_size]T,
18 allocator: &Allocator,18 allocator: &Allocator,
1919
20 pub fn init(l: &Self, allocator: &Allocator) {20 pub fn init(l: &Self, allocator: &Allocator) {
...@@ -31,17 +31,17 @@ pub struct SmallList(T: type, STATIC_SIZE: usize) {...@@ -31,17 +31,17 @@ pub struct SmallList(T: type, STATIC_SIZE: usize) {
3131
32 pub fn append(l: &Self, item: T) -> %void {32 pub fn append(l: &Self, item: T) -> %void {
33 const new_length = l.len + 1;33 const new_length = l.len + 1;
34 %return l.ensure_capacity(new_length);34 %return l.ensureCapacity(new_length);
35 l.items[l.len] = item;35 l.items[l.len] = item;
36 l.len = new_length;36 l.len = new_length;
37 }37 }
3838
39 pub fn resize(l: &Self, new_len: usize) -> %void {39 pub fn resize(l: &Self, new_len: usize) -> %void {
40 %return l.ensure_capacity(new_len);40 %return l.ensureCapacity(new_len);
41 l.len = new_len;41 l.len = new_len;
42 }42 }
4343
44 pub fn ensure_capacity(l: &Self, new_capacity: usize) -> %void {44 pub fn ensureCapacity(l: &Self, new_capacity: usize) -> %void {
45 const old_capacity = l.items.len;45 const old_capacity = l.items.len;
46 var better_capacity = old_capacity;46 var better_capacity = old_capacity;
47 while (better_capacity < new_capacity) {47 while (better_capacity < new_capacity) {
...@@ -59,7 +59,7 @@ pub struct SmallList(T: type, STATIC_SIZE: usize) {...@@ -59,7 +59,7 @@ pub struct SmallList(T: type, STATIC_SIZE: usize) {
59}59}
6060
61#attribute("test")61#attribute("test")
62fn basic_list_test() {62fn basicListTest() {
63 var list: List(i32) = undefined;63 var list: List(i32) = undefined;
64 list.init(&debug.global_allocator);64 list.init(&debug.global_allocator);
65 defer list.deinit();65 defer list.deinit();
std/math.zig+6-34
...@@ -4,34 +4,6 @@ pub enum Cmp {...@@ -4,34 +4,6 @@ pub enum Cmp {
4 Less,4 Less,
5}5}
66
7pub fn f64_from_bits(bits: u64) -> f64 {
8 *(&f64)(&bits)
9}
10
11pub fn f64_to_bits(f: f64) -> u64 {
12 *(&u64)(&f)
13}
14
15pub fn f64_get_pos_inf() -> f64 {
16 f64_from_bits(0x7FF0000000000000)
17}
18
19pub fn f64_get_neg_inf() -> f64 {
20 f64_from_bits(0xFFF0000000000000)
21}
22
23pub fn f64_is_nan(f: f64) -> bool {
24 const bits = f64_to_bits(f);
25 const exp: i64 = i64((bits >> 52) & ((1 << 11) - 1));
26 const sig = (bits & ((1 << 52) - 1)) | (1 << 52);
27
28 sig != 0 && exp == (1 << 11) - 1
29}
30
31pub fn f64_is_inf(f: f64) -> bool {
32 f == f64_get_neg_inf() || f == f64_get_pos_inf()
33}
34
35pub fn min(inline T: type, x: T, y: T) -> T {7pub fn min(inline T: type, x: T, y: T) -> T {
36 if (x < y) x else y8 if (x < y) x else y
37}9}
...@@ -41,15 +13,15 @@ pub fn max(inline T: type, x: T, y: T) -> T {...@@ -41,15 +13,15 @@ pub fn max(inline T: type, x: T, y: T) -> T {
41}13}
4214
43pub error Overflow;15pub error Overflow;
44pub fn mul_overflow(inline T: type, a: T, b: T) -> %T {16pub fn mulOverflow(inline T: type, a: T, b: T) -> %T {
45 var answer: T = undefined;17 var answer: T = undefined;
46 if (@mul_with_overflow(T, a, b, &answer)) error.Overflow else answer18 if (@mulWithOverflow(T, a, b, &answer)) error.Overflow else answer
47}19}
48pub fn add_overflow(inline T: type, a: T, b: T) -> %T {20pub fn addOverflow(inline T: type, a: T, b: T) -> %T {
49 var answer: T = undefined;21 var answer: T = undefined;
50 if (@add_with_overflow(T, a, b, &answer)) error.Overflow else answer22 if (@addWithOverflow(T, a, b, &answer)) error.Overflow else answer
51}23}
52pub fn sub_overflow(inline T: type, a: T, b: T) -> %T {24pub fn subOverflow(inline T: type, a: T, b: T) -> %T {
53 var answer: T = undefined;25 var answer: T = undefined;
54 if (@sub_with_overflow(T, a, b, &answer)) error.Overflow else answer26 if (@subWithOverflow(T, a, b, &answer)) error.Overflow else answer
55}27}
std/mem.zig+11-11
...@@ -9,34 +9,34 @@ pub error NoMem;...@@ -9,34 +9,34 @@ pub error NoMem;
99
10pub type Context = u8;10pub type Context = u8;
11pub struct Allocator {11pub struct Allocator {
12 alloc_fn: fn (self: &Allocator, n: usize) -> %[]u8,12 allocFn: fn (self: &Allocator, n: usize) -> %[]u8,
13 realloc_fn: fn (self: &Allocator, old_mem: []u8, new_size: usize) -> %[]u8,13 reallocFn: fn (self: &Allocator, old_mem: []u8, new_size: usize) -> %[]u8,
14 free_fn: fn (self: &Allocator, mem: []u8),14 freeFn: fn (self: &Allocator, mem: []u8),
15 context: ?&Context,15 context: ?&Context,
1616
17 /// Aborts the program if an allocation fails.17 /// Aborts the program if an allocation fails.
18 fn checked_alloc(self: &Allocator, inline T: type, n: usize) -> []T {18 fn checkedAlloc(self: &Allocator, inline T: type, n: usize) -> []T {
19 alloc(self, T, n) %% |err| {19 alloc(self, T, n) %% |err| {
20 // TODO var args printf20 // TODO var args printf
21 %%io.stderr.write("allocation failure: ");21 %%io.stderr.write("allocation failure: ");
22 %%io.stderr.write(@err_name(err));22 %%io.stderr.write(@errName(err));
23 %%io.stderr.printf("\n");23 %%io.stderr.printf("\n");
24 os.abort()24 os.abort()
25 }25 }
26 }26 }
2727
28 fn alloc(self: &Allocator, inline T: type, n: usize) -> %[]T {28 fn alloc(self: &Allocator, inline T: type, n: usize) -> %[]T {
29 const byte_count = %return math.mul_overflow(usize, @sizeof(T), n);29 const byte_count = %return math.mulOverflow(usize, @sizeOf(T), n);
30 ([]T)(%return self.alloc_fn(self, byte_count))30 ([]T)(%return self.allocFn(self, byte_count))
31 }31 }
3232
33 fn realloc(self: &Allocator, inline T: type, old_mem: []T, n: usize) -> %[]T {33 fn realloc(self: &Allocator, inline T: type, old_mem: []T, n: usize) -> %[]T {
34 const byte_count = %return math.mul_overflow(usize, @sizeof(T), n);34 const byte_count = %return math.mulOverflow(usize, @sizeOf(T), n);
35 ([]T)(%return self.realloc_fn(self, ([]u8)(old_mem), byte_count))35 ([]T)(%return self.reallocFn(self, ([]u8)(old_mem), byte_count))
36 }36 }
3737
38 fn free(self: &Allocator, inline T: type, mem: []T) {38 fn free(self: &Allocator, inline T: type, mem: []T) {
39 self.free_fn(self, ([]u8)(mem));39 self.freeFn(self, ([]u8)(mem));
40 }40 }
41}41}
4242
...@@ -44,7 +44,7 @@ pub struct Allocator {...@@ -44,7 +44,7 @@ pub struct Allocator {
44/// dest.len must be >= source.len.44/// dest.len must be >= source.len.
45pub fn copy(inline T: type, dest: []T, source: []const T) {45pub fn copy(inline T: type, dest: []T, source: []const T) {
46 assert(dest.len >= source.len);46 assert(dest.len >= source.len);
47 @memcpy(dest.ptr, source.ptr, @sizeof(T) * source.len);47 @memcpy(dest.ptr, source.ptr, @sizeOf(T) * source.len);
48}48}
4949
50/// Return < 0, == 0, or > 0 if memory a is less than, equal to, or greater than,50/// Return < 0, == 0, or > 0 if memory a is less than, equal to, or greater than,
std/net.zig+43-43
...@@ -17,7 +17,7 @@ struct Connection {...@@ -17,7 +17,7 @@ struct Connection {
1717
18 pub fn send(c: Connection, buf: []const u8) -> %usize {18 pub fn send(c: Connection, buf: []const u8) -> %usize {
19 const send_ret = linux.sendto(c.socket_fd, buf.ptr, buf.len, 0, null, 0);19 const send_ret = linux.sendto(c.socket_fd, buf.ptr, buf.len, 0, null, 0);
20 const send_err = linux.get_errno(send_ret);20 const send_err = linux.getErrno(send_ret);
21 switch (send_err) {21 switch (send_err) {
22 0 => return send_ret,22 0 => return send_ret,
23 errno.EINVAL => unreachable{},23 errno.EINVAL => unreachable{},
...@@ -31,7 +31,7 @@ struct Connection {...@@ -31,7 +31,7 @@ struct Connection {
3131
32 pub fn recv(c: Connection, buf: []u8) -> %[]u8 {32 pub fn recv(c: Connection, buf: []u8) -> %[]u8 {
33 const recv_ret = linux.recvfrom(c.socket_fd, buf.ptr, buf.len, 0, null, null);33 const recv_ret = linux.recvfrom(c.socket_fd, buf.ptr, buf.len, 0, null, null);
34 const recv_err = linux.get_errno(recv_ret);34 const recv_err = linux.getErrno(recv_ret);
35 switch (recv_err) {35 switch (recv_err) {
36 0 => return buf[0...recv_ret],36 0 => return buf[0...recv_ret],
37 errno.EINVAL => unreachable{},37 errno.EINVAL => unreachable{},
...@@ -47,7 +47,7 @@ struct Connection {...@@ -47,7 +47,7 @@ struct Connection {
47 }47 }
4848
49 pub fn close(c: Connection) -> %void {49 pub fn close(c: Connection) -> %void {
50 switch (linux.get_errno(linux.close(c.socket_fd))) {50 switch (linux.getErrno(linux.close(c.socket_fd))) {
51 0 => return,51 0 => return,
52 errno.EBADF => unreachable{},52 errno.EBADF => unreachable{},
53 errno.EINTR => return error.SigInterrupt,53 errno.EINTR => return error.SigInterrupt,
...@@ -76,7 +76,7 @@ pub fn lookup(hostname: []const u8, out_addrs: []Address) -> %[]Address {...@@ -76,7 +76,7 @@ pub fn lookup(hostname: []const u8, out_addrs: []Address) -> %[]Address {
76 unreachable{} // TODO76 unreachable{} // TODO
77 }77 }
7878
79 switch (parse_ip_literal(hostname)) {79 switch (parseIpLiteral(hostname)) {
80 Ok => |addr| {80 Ok => |addr| {
81 out_addrs[0] = addr;81 out_addrs[0] = addr;
82 return out_addrs[0...1];82 return out_addrs[0...1];
...@@ -87,9 +87,9 @@ pub fn lookup(hostname: []const u8, out_addrs: []Address) -> %[]Address {...@@ -87,9 +87,9 @@ pub fn lookup(hostname: []const u8, out_addrs: []Address) -> %[]Address {
87 unreachable{} // TODO87 unreachable{} // TODO
88}88}
8989
90pub fn connect_addr(addr: &Address, port: u16) -> %Connection {90pub fn connectAddr(addr: &Address, port: u16) -> %Connection {
91 const socket_ret = linux.socket(addr.family, linux.SOCK_STREAM, linux.PROTO_tcp);91 const socket_ret = linux.socket(addr.family, linux.SOCK_STREAM, linux.PROTO_tcp);
92 const socket_err = linux.get_errno(socket_ret);92 const socket_err = linux.getErrno(socket_ret);
93 if (socket_err > 0) {93 if (socket_err > 0) {
94 // TODO figure out possible errors from socket()94 // TODO figure out possible errors from socket()
95 return error.Unexpected;95 return error.Unexpected;
...@@ -99,22 +99,22 @@ pub fn connect_addr(addr: &Address, port: u16) -> %Connection {...@@ -99,22 +99,22 @@ pub fn connect_addr(addr: &Address, port: u16) -> %Connection {
99 const connect_ret = if (addr.family == linux.AF_INET) {99 const connect_ret = if (addr.family == linux.AF_INET) {
100 var os_addr: linux.sockaddr_in = undefined;100 var os_addr: linux.sockaddr_in = undefined;
101 os_addr.family = addr.family;101 os_addr.family = addr.family;
102 os_addr.port = swap_if_little_endian(u16, port);102 os_addr.port = swapIfLittleEndian(u16, port);
103 @memcpy((&u8)(&os_addr.addr), &addr.addr[0], 4);103 @memcpy((&u8)(&os_addr.addr), &addr.addr[0], 4);
104 @memset(&os_addr.zero, 0, @sizeof(@typeof(os_addr.zero)));104 @memset(&os_addr.zero, 0, @sizeOf(@typeOf(os_addr.zero)));
105 linux.connect(socket_fd, (&linux.sockaddr)(&os_addr), @sizeof(linux.sockaddr_in))105 linux.connect(socket_fd, (&linux.sockaddr)(&os_addr), @sizeOf(linux.sockaddr_in))
106 } else if (addr.family == linux.AF_INET6) {106 } else if (addr.family == linux.AF_INET6) {
107 var os_addr: linux.sockaddr_in6 = undefined;107 var os_addr: linux.sockaddr_in6 = undefined;
108 os_addr.family = addr.family;108 os_addr.family = addr.family;
109 os_addr.port = swap_if_little_endian(u16, port);109 os_addr.port = swapIfLittleEndian(u16, port);
110 os_addr.flowinfo = 0;110 os_addr.flowinfo = 0;
111 os_addr.scope_id = addr.scope_id;111 os_addr.scope_id = addr.scope_id;
112 @memcpy(&os_addr.addr[0], &addr.addr[0], 16);112 @memcpy(&os_addr.addr[0], &addr.addr[0], 16);
113 linux.connect(socket_fd, (&linux.sockaddr)(&os_addr), @sizeof(linux.sockaddr_in6))113 linux.connect(socket_fd, (&linux.sockaddr)(&os_addr), @sizeOf(linux.sockaddr_in6))
114 } else {114 } else {
115 unreachable{}115 unreachable{}
116 };116 };
117 const connect_err = linux.get_errno(connect_ret);117 const connect_err = linux.getErrno(connect_ret);
118 if (connect_err > 0) {118 if (connect_err > 0) {
119 switch (connect_err) {119 switch (connect_err) {
120 errno.ETIMEDOUT => return error.TimedOut,120 errno.ETIMEDOUT => return error.TimedOut,
...@@ -135,23 +135,23 @@ pub fn connect(hostname: []const u8, port: u16) -> %Connection {...@@ -135,23 +135,23 @@ pub fn connect(hostname: []const u8, port: u16) -> %Connection {
135 const addrs_slice = %return lookup(hostname, addrs_buf);135 const addrs_slice = %return lookup(hostname, addrs_buf);
136 const main_addr = &addrs_slice[0];136 const main_addr = &addrs_slice[0];
137137
138 return connect_addr(main_addr, port);138 return connectAddr(main_addr, port);
139}139}
140140
141pub error InvalidIpLiteral;141pub error InvalidIpLiteral;
142142
143pub fn parse_ip_literal(buf: []const u8) -> %Address {143pub fn parseIpLiteral(buf: []const u8) -> %Address {
144 switch (parse_ip4(buf)) {144 switch (parseIp4(buf)) {
145 Ok => |ip4| {145 Ok => |ip4| {
146 var result: Address = undefined;146 var result: Address = undefined;
147 @memcpy(&result.addr[0], (&u8)(&ip4), @sizeof(u32));147 @memcpy(&result.addr[0], (&u8)(&ip4), @sizeOf(u32));
148 result.family = linux.AF_INET;148 result.family = linux.AF_INET;
149 result.scope_id = 0;149 result.scope_id = 0;
150 return result;150 return result;
151 },151 },
152 else => {},152 else => {},
153 }153 }
154 switch (parse_ip6(buf)) {154 switch (parseIp6(buf)) {
155 Ok => |addr| {155 Ok => |addr| {
156 return addr;156 return addr;
157 },157 },
...@@ -161,7 +161,7 @@ pub fn parse_ip_literal(buf: []const u8) -> %Address {...@@ -161,7 +161,7 @@ pub fn parse_ip_literal(buf: []const u8) -> %Address {
161 return error.InvalidIpLiteral;161 return error.InvalidIpLiteral;
162}162}
163163
164fn hex_digit(c: u8) -> u8 {164fn hexDigit(c: u8) -> u8 {
165 // TODO use switch with range165 // TODO use switch with range
166 if ('0' <= c && c <= '9') {166 if ('0' <= c && c <= '9') {
167 c - '0'167 c - '0'
...@@ -170,7 +170,7 @@ fn hex_digit(c: u8) -> u8 {...@@ -170,7 +170,7 @@ fn hex_digit(c: u8) -> u8 {
170 } else if ('a' <= c && c <= 'z') {170 } else if ('a' <= c && c <= 'z') {
171 c - 'a' + 10171 c - 'a' + 10
172 } else {172 } else {
173 @max_value(u8)173 @maxValue(u8)
174 }174 }
175}175}
176176
...@@ -180,7 +180,7 @@ error JunkAtEnd;...@@ -180,7 +180,7 @@ error JunkAtEnd;
180error Incomplete;180error Incomplete;
181181
182#static_eval_enable(false)182#static_eval_enable(false)
183fn parse_ip6(buf: []const u8) -> %Address {183fn parseIp6(buf: []const u8) -> %Address {
184 var result: Address = undefined;184 var result: Address = undefined;
185 result.family = linux.AF_INET6;185 result.family = linux.AF_INET6;
186 result.scope_id = 0;186 result.scope_id = 0;
...@@ -194,10 +194,10 @@ fn parse_ip6(buf: []const u8) -> %Address {...@@ -194,10 +194,10 @@ fn parse_ip6(buf: []const u8) -> %Address {
194 if (scope_id) {194 if (scope_id) {
195 if (c >= '0' && c <= '9') {195 if (c >= '0' && c <= '9') {
196 const digit = c - '0';196 const digit = c - '0';
197 if (@mul_with_overflow(u32, result.scope_id, 10, &result.scope_id)) {197 if (@mulWithOverflow(u32, result.scope_id, 10, &result.scope_id)) {
198 return error.Overflow;198 return error.Overflow;
199 }199 }
200 if (@add_with_overflow(u32, result.scope_id, digit, &result.scope_id)) {200 if (@addWithOverflow(u32, result.scope_id, digit, &result.scope_id)) {
201 return error.Overflow;201 return error.Overflow;
202 }202 }
203 } else {203 } else {
...@@ -230,14 +230,14 @@ fn parse_ip6(buf: []const u8) -> %Address {...@@ -230,14 +230,14 @@ fn parse_ip6(buf: []const u8) -> %Address {
230 scope_id = true;230 scope_id = true;
231 saw_any_digits = false;231 saw_any_digits = false;
232 } else {232 } else {
233 const digit = hex_digit(c);233 const digit = hexDigit(c);
234 if (digit == @max_value(u8)) {234 if (digit == @maxValue(u8)) {
235 return error.InvalidChar;235 return error.InvalidChar;
236 }236 }
237 if (@mul_with_overflow(u16, x, 16, &x)) {237 if (@mulWithOverflow(u16, x, 16, &x)) {
238 return error.Overflow;238 return error.Overflow;
239 }239 }
240 if (@add_with_overflow(u16, x, digit, &x)) {240 if (@addWithOverflow(u16, x, digit, &x)) {
241 return error.Overflow;241 return error.Overflow;
242 }242 }
243 saw_any_digits = true;243 saw_any_digits = true;
...@@ -276,7 +276,7 @@ fn parse_ip6(buf: []const u8) -> %Address {...@@ -276,7 +276,7 @@ fn parse_ip6(buf: []const u8) -> %Address {
276 return error.Incomplete;276 return error.Incomplete;
277}277}
278278
279fn parse_ip4(buf: []const u8) -> %u32 {279fn parseIp4(buf: []const u8) -> %u32 {
280 var result: u32 = undefined;280 var result: u32 = undefined;
281 const out_ptr = ([]u8)((&result)[0...1]);281 const out_ptr = ([]u8)((&result)[0...1]);
282282
...@@ -298,10 +298,10 @@ fn parse_ip4(buf: []const u8) -> %u32 {...@@ -298,10 +298,10 @@ fn parse_ip4(buf: []const u8) -> %u32 {
298 } else if (c >= '0' && c <= '9') {298 } else if (c >= '0' && c <= '9') {
299 saw_any_digits = true;299 saw_any_digits = true;
300 const digit = c - '0';300 const digit = c - '0';
301 if (@mul_with_overflow(u8, x, 10, &x)) {301 if (@mulWithOverflow(u8, x, 10, &x)) {
302 return error.Overflow;302 return error.Overflow;
303 }303 }
304 if (@add_with_overflow(u8, x, digit, &x)) {304 if (@addWithOverflow(u8, x, digit, &x)) {
305 return error.Overflow;305 return error.Overflow;
306 }306 }
307 } else {307 } else {
...@@ -318,19 +318,19 @@ fn parse_ip4(buf: []const u8) -> %u32 {...@@ -318,19 +318,19 @@ fn parse_ip4(buf: []const u8) -> %u32 {
318318
319319
320#attribute("test")320#attribute("test")
321fn test_parse_ip4() {321fn testParseIp4() {
322 assert(%%parse_ip4("127.0.0.1") == swap_if_little_endian(u32, 0x7f000001));322 assert(%%parseIp4("127.0.0.1") == swapIfLittleEndian(u32, 0x7f000001));
323 switch (parse_ip4("256.0.0.1")) { Overflow => {}, else => unreachable {}, }323 switch (parseIp4("256.0.0.1")) { Overflow => {}, else => unreachable {}, }
324 switch (parse_ip4("x.0.0.1")) { InvalidChar => {}, else => unreachable {}, }324 switch (parseIp4("x.0.0.1")) { InvalidChar => {}, else => unreachable {}, }
325 switch (parse_ip4("127.0.0.1.1")) { JunkAtEnd => {}, else => unreachable {}, }325 switch (parseIp4("127.0.0.1.1")) { JunkAtEnd => {}, else => unreachable {}, }
326 switch (parse_ip4("127.0.0.")) { Incomplete => {}, else => unreachable {}, }326 switch (parseIp4("127.0.0.")) { Incomplete => {}, else => unreachable {}, }
327 switch (parse_ip4("100..0.1")) { InvalidChar => {}, else => unreachable {}, }327 switch (parseIp4("100..0.1")) { InvalidChar => {}, else => unreachable {}, }
328}328}
329329
330#attribute("test")330#attribute("test")
331fn test_parse_ip6() {331fn testParseIp6() {
332 {332 {
333 const addr = %%parse_ip6("FF01:0:0:0:0:0:0:FB");333 const addr = %%parseIp6("FF01:0:0:0:0:0:0:FB");
334 assert(addr.addr[0] == 0xff);334 assert(addr.addr[0] == 0xff);
335 assert(addr.addr[1] == 0x01);335 assert(addr.addr[1] == 0x01);
336 assert(addr.addr[2] == 0x00);336 assert(addr.addr[2] == 0x00);
...@@ -338,7 +338,7 @@ fn test_parse_ip6() {...@@ -338,7 +338,7 @@ fn test_parse_ip6() {
338}338}
339339
340#attribute("test")340#attribute("test")
341fn test_lookup_simple_ip() {341fn testLookupSimpleIp() {
342 {342 {
343 var addrs_buf: [5]Address = undefined;343 var addrs_buf: [5]Address = undefined;
344 const addrs = %%lookup("192.168.1.1", addrs_buf);344 const addrs = %%lookup("192.168.1.1", addrs_buf);
...@@ -352,16 +352,16 @@ fn test_lookup_simple_ip() {...@@ -352,16 +352,16 @@ fn test_lookup_simple_ip() {
352 }352 }
353}353}
354354
355fn swap_if_little_endian(inline T: type, x: T) -> T {355fn swapIfLittleEndian(inline T: type, x: T) -> T {
356 if (@compile_var("is_big_endian")) x else endian_swap(T, x)356 if (@compileVar("is_big_endian")) x else endianSwap(T, x)
357}357}
358358
359fn endian_swap(inline T: type, x: T) -> T {359fn endianSwap(inline T: type, x: T) -> T {
360 const x_slice = ([]u8)((&const x)[0...1]);360 const x_slice = ([]u8)((&const x)[0...1]);
361 var result: T = undefined;361 var result: T = undefined;
362 const result_slice = ([]u8)((&result)[0...1]);362 const result_slice = ([]u8)((&result)[0...1]);
363 for (result_slice) |*b, i| {363 for (result_slice) |*b, i| {
364 *b = x_slice[@sizeof(T) - i - 1];364 *b = x_slice[@sizeOf(T) - i - 1];
365 }365 }
366 return result;366 return result;
367}367}
std/os.zig+2-2
...@@ -5,10 +5,10 @@ pub error SigInterrupt;...@@ -5,10 +5,10 @@ pub error SigInterrupt;
5pub error Unexpected;5pub error Unexpected;
66
7pub fn get_random_bytes(buf: []u8) -> %void {7pub fn get_random_bytes(buf: []u8) -> %void {
8 switch (@compile_var("os")) {8 switch (@compileVar("os")) {
9 linux => {9 linux => {
10 const ret = linux.getrandom(buf.ptr, buf.len, 0);10 const ret = linux.getrandom(buf.ptr, buf.len, 0);
11 const err = linux.get_errno(ret);11 const err = linux.getErrno(ret);
12 if (err > 0) {12 if (err > 0) {
13 return switch (err) {13 return switch (err) {
14 errno.EINVAL => unreachable{},14 errno.EINVAL => unreachable{},
std/rand.zig+29-31
...@@ -19,15 +19,13 @@ pub const MT19937_64 = MersenneTwister(...@@ -19,15 +19,13 @@ pub const MT19937_64 = MersenneTwister(
1919
20/// Use `init` to initialize this state.20/// Use `init` to initialize this state.
21pub struct Rand {21pub struct Rand {
22 const Rng = if (@sizeof(usize) >= 8) MT19937_64 else MT19937_32;22 const Rng = if (@sizeOf(usize) >= 8) MT19937_64 else MT19937_32;
2323
24 rng: Rng,24 rng: Rng,
2525
26 /// Initialize random state with the given seed.26 /// Initialize random state with the given seed.
27 pub fn init(seed: usize) -> Rand {27 pub fn init(r: &Rand, seed: usize) {
28 var r: Rand = undefined;28 r.rng.init(seed);
29 r.rng = Rng.init(seed);
30 return r;
31 }29 }
3230
33 /// Get an integer with random bits.31 /// Get an integer with random bits.
...@@ -35,24 +33,24 @@ pub struct Rand {...@@ -35,24 +33,24 @@ pub struct Rand {
35 if (T == usize) {33 if (T == usize) {
36 return r.rng.get();34 return r.rng.get();
37 } else {35 } else {
38 var result: [@sizeof(T)]u8 = undefined;36 var result: [@sizeOf(T)]u8 = undefined;
39 r.fill_bytes(result);37 r.fillBytes(result);
40 return ([]T)(result)[0];38 return ([]T)(result)[0];
41 }39 }
42 }40 }
4341
44 /// Fill `buf` with randomness.42 /// Fill `buf` with randomness.
45 pub fn fill_bytes(r: &Rand, buf: []u8) {43 pub fn fillBytes(r: &Rand, buf: []u8) {
46 var bytes_left = buf.len;44 var bytes_left = buf.len;
47 while (bytes_left >= @sizeof(usize)) {45 while (bytes_left >= @sizeOf(usize)) {
48 ([]usize)(buf[buf.len - bytes_left...])[0] = r.rng.get();46 ([]usize)(buf[buf.len - bytes_left...])[0] = r.rng.get();
49 bytes_left -= @sizeof(usize);47 bytes_left -= @sizeOf(usize);
50 }48 }
51 if (bytes_left > 0) {49 if (bytes_left > 0) {
52 var rand_val_array : [@sizeof(usize)]u8 = undefined;50 var rand_val_array : [@sizeOf(usize)]u8 = undefined;
53 ([]usize)(rand_val_array)[0] = r.rng.get();51 ([]usize)(rand_val_array)[0] = r.rng.get();
54 while (bytes_left > 0) {52 while (bytes_left > 0) {
55 buf[buf.len - bytes_left] = rand_val_array[@sizeof(usize) - bytes_left];53 buf[buf.len - bytes_left] = rand_val_array[@sizeOf(usize) - bytes_left];
56 bytes_left -= 1;54 bytes_left -= 1;
57 }55 }
58 }56 }
...@@ -61,14 +59,14 @@ pub struct Rand {...@@ -61,14 +59,14 @@ pub struct Rand {
61 /// Get a random unsigned integer with even distribution between `start`59 /// Get a random unsigned integer with even distribution between `start`
62 /// inclusive and `end` exclusive.60 /// inclusive and `end` exclusive.
63 // TODO support signed integers and then rename to "range"61 // TODO support signed integers and then rename to "range"
64 pub fn range_unsigned(r: &Rand, inline T: type, start: T, end: T) -> T {62 pub fn rangeUnsigned(r: &Rand, inline T: type, start: T, end: T) -> T {
65 const range = end - start;63 const range = end - start;
66 const leftover = @max_value(T) % range;64 const leftover = @maxValue(T) % range;
67 const upper_bound = @max_value(T) - leftover;65 const upper_bound = @maxValue(T) - leftover;
68 var rand_val_array : [@sizeof(T)]u8 = undefined;66 var rand_val_array : [@sizeOf(T)]u8 = undefined;
6967
70 while (true) {68 while (true) {
71 r.fill_bytes(rand_val_array);69 r.fillBytes(rand_val_array);
72 const rand_val = ([]T)(rand_val_array)[0];70 const rand_val = ([]T)(rand_val_array)[0];
73 if (rand_val < upper_bound) {71 if (rand_val < upper_bound) {
74 return start + (rand_val % range);72 return start + (rand_val % range);
...@@ -79,19 +77,19 @@ pub struct Rand {...@@ -79,19 +77,19 @@ pub struct Rand {
79 /// Get a floating point value in the range 0.0..1.0.77 /// Get a floating point value in the range 0.0..1.0.
80 pub fn float(r: &Rand, inline T: type) -> T {78 pub fn float(r: &Rand, inline T: type) -> T {
81 // TODO Implement this way instead:79 // TODO Implement this way instead:
82 // const int = @int_type(false, @sizeof(T) * 8);80 // const int = @int_type(false, @sizeOf(T) * 8);
83 // const mask = ((1 << @float_mantissa_bit_count(T)) - 1);81 // const mask = ((1 << @float_mantissa_bit_count(T)) - 1);
84 // const rand_bits = r.rng.scalar(int) & mask;82 // const rand_bits = r.rng.scalar(int) & mask;
85 // return @float_compose(T, false, 0, rand_bits) - 1.083 // return @float_compose(T, false, 0, rand_bits) - 1.0
86 const int_type = @int_type(false, @sizeof(T) * 8);84 const int_type = @intType(false, @sizeOf(T) * 8);
87 const precision = if (T == f32) {85 const precision = if (T == f32) {
88 1677721686 16777216
89 } else if (T == f64) {87 } else if (T == f64) {
90 900719925474099288 9007199254740992
91 } else {89 } else {
92 @compile_err("unknown floating point type" ++ @type_name(T))90 @compile_err("unknown floating point type" ++ @typeName(T))
93 };91 };
94 return T(r.range_unsigned(int_type, 0, precision)) / T(precision);92 return T(r.rangeUnsigned(int_type, 0, precision)) / T(precision);
95 }93 }
96}94}
9795
...@@ -110,8 +108,7 @@ struct MersenneTwister(...@@ -110,8 +108,7 @@ struct MersenneTwister(
110108
111 // TODO improve compile time eval code and then allow this function to be executed at compile time.109 // TODO improve compile time eval code and then allow this function to be executed at compile time.
112 #static_eval_enable(false)110 #static_eval_enable(false)
113 pub fn init(seed: int) -> Self {111 pub fn init(mt: &Self, seed: int) {
114 var mt: Self = undefined;
115 mt.index = n;112 mt.index = n;
116113
117 var prev_value = seed;114 var prev_value = seed;
...@@ -120,8 +117,6 @@ struct MersenneTwister(...@@ -120,8 +117,6 @@ struct MersenneTwister(
120 prev_value = int(i) +% f *% (prev_value ^ (prev_value >> (int.bit_count - 2)));117 prev_value = int(i) +% f *% (prev_value ^ (prev_value >> (int.bit_count - 2)));
121 mt.array[i] = prev_value;118 mt.array[i] = prev_value;
122 }};119 }};
123
124 return mt;
125 }120 }
126121
127 pub fn get(mt: &Self) -> int {122 pub fn get(mt: &Self) -> int {
...@@ -161,8 +156,9 @@ struct MersenneTwister(...@@ -161,8 +156,9 @@ struct MersenneTwister(
161}156}
162157
163#attribute("test")158#attribute("test")
164fn test_float32() {159fn testFloat32() {
165 var r = Rand.init(42);160 var r: Rand = undefined;
161 r.init(42);
166162
167 {var i: usize = 0; while (i < 1000; i += 1) {163 {var i: usize = 0; while (i < 1000; i += 1) {
168 const val = r.float(f32);164 const val = r.float(f32);
...@@ -172,16 +168,18 @@ fn test_float32() {...@@ -172,16 +168,18 @@ fn test_float32() {
172}168}
173169
174#attribute("test")170#attribute("test")
175fn test_MT19937_64() {171fn testMT19937_64() {
176 const rng = MT19937_64.init(rand_test.mt64_seed);172 var rng: MT19937_64 = undefined;
173 rng.init(rand_test.mt64_seed);
177 for (rand_test.mt64_data) |value| {174 for (rand_test.mt64_data) |value| {
178 assert(value == rng.get());175 assert(value == rng.get());
179 }176 }
180}177}
181178
182#attribute("test")179#attribute("test")
183fn test_MT19937_32() {180fn testMT19937_32() {
184 const rng = MT19937_32.init(rand_test.mt32_seed);181 var rng: MT19937_32 = undefined;
182 rng.init(rand_test.mt32_seed);
185 for (rand_test.mt32_data) |value| {183 for (rand_test.mt32_data) |value| {
186 assert(value == rng.get());184 assert(value == rng.get());
187 }185 }
std/str.zig+3-3
...@@ -1,10 +1,10 @@...@@ -1,10 +1,10 @@
1const assert = @import("debug.zig").assert;1const assert = @import("debug.zig").assert;
22
3pub fn eql(a: []const u8, b: []const u8) -> bool {3pub fn eql(a: []const u8, b: []const u8) -> bool {
4 slice_eql(u8, a, b)4 sliceEql(u8, a, b)
5}5}
66
7pub fn slice_eql(inline T: type, a: []const T, b: []const T) -> bool {7pub fn sliceEql(inline T: type, a: []const T, b: []const T) -> bool {
8 if (a.len != b.len) return false;8 if (a.len != b.len) return false;
9 for (a) |item, index| {9 for (a) |item, index| {
10 if (b[index] != item) return false;10 if (b[index] != item) return false;
...@@ -13,7 +13,7 @@ pub fn slice_eql(inline T: type, a: []const T, b: []const T) -> bool {...@@ -13,7 +13,7 @@ pub fn slice_eql(inline T: type, a: []const T, b: []const T) -> bool {
13}13}
1414
15#attribute("test")15#attribute("test")
16fn string_equality() {16fn stringEquality() {
17 assert(eql("abcd", "abcd"));17 assert(eql("abcd", "abcd"));
18 assert(!eql("abcdef", "abZdef"));18 assert(!eql("abcdef", "abZdef"));
19 assert(!eql("abcdefg", "abcdef"));19 assert(!eql("abcdefg", "abcdef"));
std/test_runner.zig+4-4
...@@ -7,19 +7,19 @@ struct TestFn {...@@ -7,19 +7,19 @@ struct TestFn {
77
8extern var zig_test_fn_list: []TestFn;8extern var zig_test_fn_list: []TestFn;
99
10pub fn run_tests() -> %void {10pub fn runTests() -> %void {
11 for (zig_test_fn_list) |test_fn, i| {11 for (zig_test_fn_list) |testFn, i| {
12 // TODO: print var args12 // TODO: print var args
13 %%io.stderr.write("Test ");13 %%io.stderr.write("Test ");
14 %%io.stderr.print_u64(i + 1);14 %%io.stderr.print_u64(i + 1);
15 %%io.stderr.write("/");15 %%io.stderr.write("/");
16 %%io.stderr.print_u64(zig_test_fn_list.len);16 %%io.stderr.print_u64(zig_test_fn_list.len);
17 %%io.stderr.write(" ");17 %%io.stderr.write(" ");
18 %%io.stderr.write(test_fn.name);18 %%io.stderr.write(testFn.name);
19 %%io.stderr.write("...");19 %%io.stderr.write("...");
20 %%io.stderr.flush();20 %%io.stderr.flush();
2121
22 test_fn.func();22 testFn.func();
2323
2424
25 %%io.stderr.write("OK\n");25 %%io.stderr.write("OK\n");
std/test_runner_libc.zig+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const test_runner = @import("test_runner.zig");1const test_runner = @import("test_runner.zig");
22
3export fn main(argc: c_int, argv: &&u8) -> c_int {3export fn main(argc: c_int, argv: &&u8) -> c_int {
4 test_runner.run_tests() %% return -1;4 test_runner.runTests() %% return -1;
5 return 0;5 return 0;
6}6}
std/test_runner_nolibc.zig+1-1
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const test_runner = @import("test_runner.zig");1const test_runner = @import("test_runner.zig");
22
3pub fn main(args: [][]u8) -> %void {3pub fn main(args: [][]u8) -> %void {
4 return test_runner.run_tests();4 return test_runner.runTests();
5}5}
test/cases/sizeof_and_typeof.zig created+9
...@@ -0,0 +1,9 @@
1const assert = @import("std").debug.assert;
2
3#attribute("test")
4fn sizeofAndTypeOf() {
5 const y: @typeOf(x) = 120;
6 assert(@sizeOf(@typeOf(y)) == 2);
7}
8const x: u16 = 13;
9const z: @typeOf(x) = 19;
test/run_tests.cpp+35-35
...@@ -202,7 +202,7 @@ static TestCase *add_parseh_case(const char *case_name, const char *source, int...@@ -202,7 +202,7 @@ static TestCase *add_parseh_case(const char *case_name, const char *source, int
202202
203static void add_compiling_test_cases(void) {203static void add_compiling_test_cases(void) {
204 add_simple_case_libc("hello world with libc", R"SOURCE(204 add_simple_case_libc("hello world with libc", R"SOURCE(
205const c = @c_import(@c_include("stdio.h"));205const c = @cImport(@cInclude("stdio.h"));
206export fn main(argc: c_int, argv: &&u8) -> c_int {206export fn main(argc: c_int, argv: &&u8) -> c_int {
207 c.puts(c"Hello, world!");207 c.puts(c"Hello, world!");
208 return 0;208 return 0;
...@@ -215,12 +215,12 @@ use @import("std").io;...@@ -215,12 +215,12 @@ use @import("std").io;
215use @import("foo.zig");215use @import("foo.zig");
216216
217pub fn main(args: [][]u8) -> %void {217pub fn main(args: [][]u8) -> %void {
218 private_function();218 privateFunction();
219 %%stdout.printf("OK 2\n");219 %%stdout.printf("OK 2\n");
220}220}
221221
222fn private_function() {222fn privateFunction() {
223 print_text();223 printText();
224}224}
225 )SOURCE", "OK 1\nOK 2\n");225 )SOURCE", "OK 1\nOK 2\n");
226226
...@@ -229,12 +229,12 @@ use @import("std").io;...@@ -229,12 +229,12 @@ use @import("std").io;
229229
230// purposefully conflicting function with main.zig230// purposefully conflicting function with main.zig
231// but it's private so it should be OK231// but it's private so it should be OK
232fn private_function() {232fn privateFunction() {
233 %%stdout.printf("OK 1\n");233 %%stdout.printf("OK 1\n");
234}234}
235235
236pub fn print_text() {236pub fn printText() {
237 private_function();237 privateFunction();
238}238}
239 )SOURCE");239 )SOURCE");
240 }240 }
...@@ -316,7 +316,7 @@ pub fn main(args: [][]u8) -> %void {...@@ -316,7 +316,7 @@ pub fn main(args: [][]u8) -> %void {
316316
317317
318 add_simple_case_libc("number literals", R"SOURCE(318 add_simple_case_libc("number literals", R"SOURCE(
319const c = @c_import(@c_include("stdio.h"));319const c = @cImport(@cInclude("stdio.h"));
320320
321export fn main(argc: c_int, argv: &&u8) -> c_int {321export fn main(argc: c_int, argv: &&u8) -> c_int {
322 c.printf(c"\n");322 c.printf(c"\n");
...@@ -444,12 +444,12 @@ export fn main(argc: c_int, argv: &&u8) -> c_int {...@@ -444,12 +444,12 @@ export fn main(argc: c_int, argv: &&u8) -> c_int {
444 add_simple_case("order-independent declarations", R"SOURCE(444 add_simple_case("order-independent declarations", R"SOURCE(
445const io = @import("std").io;445const io = @import("std").io;
446const z = io.stdin_fileno;446const z = io.stdin_fileno;
447const x : @typeof(y) = 1234;447const x : @typeOf(y) = 1234;
448const y : u16 = 5678;448const y : u16 = 5678;
449pub fn main(args: [][]u8) -> %void {449pub fn main(args: [][]u8) -> %void {
450 var x_local : i32 = print_ok(x);450 var x_local : i32 = print_ok(x);
451}451}
452fn print_ok(val: @typeof(x)) -> @typeof(foo) {452fn print_ok(val: @typeOf(x)) -> @typeOf(foo) {
453 %%io.stdout.printf("OK\n");453 %%io.stdout.printf("OK\n");
454 return 0;454 return 0;
455}455}
...@@ -482,7 +482,7 @@ pub fn main(args: [][]u8) -> %void {...@@ -482,7 +482,7 @@ pub fn main(args: [][]u8) -> %void {
482 )SOURCE", "9\n8\n7\n6\n0\n1\n2\n3\n9\n8\n7\n6\n0\n1\n2\n3\n");482 )SOURCE", "9\n8\n7\n6\n0\n1\n2\n3\n9\n8\n7\n6\n0\n1\n2\n3\n");
483483
484 add_simple_case_libc("expose function pointer to C land", R"SOURCE(484 add_simple_case_libc("expose function pointer to C land", R"SOURCE(
485const c = @c_import(@c_include("stdlib.h"));485const c = @cImport(@cInclude("stdlib.h"));
486486
487export fn compare_fn(a: ?&const c_void, b: ?&const c_void) -> c_int {487export fn compare_fn(a: ?&const c_void, b: ?&const c_void) -> c_int {
488 const a_int = (&i32)(a ?? unreachable{});488 const a_int = (&i32)(a ?? unreachable{});
...@@ -499,7 +499,7 @@ export fn compare_fn(a: ?&const c_void, b: ?&const c_void) -> c_int {...@@ -499,7 +499,7 @@ export fn compare_fn(a: ?&const c_void, b: ?&const c_void) -> c_int {
499export fn main(args: c_int, argv: &&u8) -> c_int {499export fn main(args: c_int, argv: &&u8) -> c_int {
500 var array = []u32 { 1, 7, 3, 2, 0, 9, 4, 8, 6, 5 };500 var array = []u32 { 1, 7, 3, 2, 0, 9, 4, 8, 6, 5 };
501501
502 c.qsort((&c_void)(&array[0]), c_ulong(array.len), @sizeof(i32), compare_fn);502 c.qsort((&c_void)(&array[0]), c_ulong(array.len), @sizeOf(i32), compare_fn);
503503
504 for (array) |item, i| {504 for (array) |item, i| {
505 if (item != i) {505 if (item != i) {
...@@ -514,7 +514,7 @@ export fn main(args: c_int, argv: &&u8) -> c_int {...@@ -514,7 +514,7 @@ export fn main(args: c_int, argv: &&u8) -> c_int {
514514
515515
516 add_simple_case_libc("casting between float and integer types", R"SOURCE(516 add_simple_case_libc("casting between float and integer types", R"SOURCE(
517const c = @c_import(@c_include("stdio.h"));517const c = @cImport(@cInclude("stdio.h"));
518export fn main(argc: c_int, argv: &&u8) -> c_int {518export fn main(argc: c_int, argv: &&u8) -> c_int {
519 const small: f32 = 3.25;519 const small: f32 = 3.25;
520 const x: f64 = small;520 const x: f64 = small;
...@@ -654,8 +654,8 @@ fn its_gonna_pass() -> %void { }...@@ -654,8 +654,8 @@ fn its_gonna_pass() -> %void { }
654654
655655
656 {656 {
657 TestCase *tc = add_simple_case("@embed_file", R"SOURCE(657 TestCase *tc = add_simple_case("@embedFile", R"SOURCE(
658const foo_txt = @embed_file("foo.txt");658const foo_txt = @embedFile("foo.txt");
659const io = @import("std").io;659const io = @import("std").io;
660660
661pub fn main(args: [][]u8) -> %void {661pub fn main(args: [][]u8) -> %void {
...@@ -956,8 +956,8 @@ fn f() -> @bogus(foo) {...@@ -956,8 +956,8 @@ fn f() -> @bogus(foo) {
956 )SOURCE", 1, ".tmp_source.zig:2:11: error: invalid builtin function: 'bogus'");956 )SOURCE", 1, ".tmp_source.zig:2:11: error: invalid builtin function: 'bogus'");
957957
958 add_compile_fail_case("top level decl dependency loop", R"SOURCE(958 add_compile_fail_case("top level decl dependency loop", R"SOURCE(
959const a : @typeof(b) = 0;959const a : @typeOf(b) = 0;
960const b : @typeof(a) = 0;960const b : @typeOf(a) = 0;
961 )SOURCE", 1, ".tmp_source.zig:2:1: error: 'a' depends on itself");961 )SOURCE", 1, ".tmp_source.zig:2:1: error: 'a' depends on itself");
962962
963 add_compile_fail_case("noalias on non pointer param", R"SOURCE(963 add_compile_fail_case("noalias on non pointer param", R"SOURCE(
...@@ -1012,8 +1012,8 @@ fn f(s: [10]u8) -> []u8 {...@@ -1012,8 +1012,8 @@ fn f(s: [10]u8) -> []u8 {
1012}1012}
1013 )SOURCE", 1, ".tmp_source.zig:3:5: error: array concatenation requires constant expression");1013 )SOURCE", 1, ".tmp_source.zig:3:5: error: array concatenation requires constant expression");
10141014
1015 add_compile_fail_case("c_import with bogus include", R"SOURCE(1015 add_compile_fail_case("@cImport with bogus include", R"SOURCE(
1016const c = @c_import(@c_include("bogus.h"));1016const c = @cImport(@cInclude("bogus.h"));
1017 )SOURCE", 2, ".tmp_source.zig:2:11: error: C import failed",1017 )SOURCE", 2, ".tmp_source.zig:2:11: error: C import failed",
1018 ".h:1:10: note: 'bogus.h' file not found");1018 ".h:1:10: note: 'bogus.h' file not found");
10191019
...@@ -1022,12 +1022,12 @@ const x = 3;...@@ -1022,12 +1022,12 @@ const x = 3;
1022const y = &x;1022const y = &x;
1023 )SOURCE", 1, ".tmp_source.zig:3:12: error: unable to get address of type '(integer literal)'");1023 )SOURCE", 1, ".tmp_source.zig:3:12: error: unable to get address of type '(integer literal)'");
10241024
1025 add_compile_fail_case("@typeof number literal", R"SOURCE(1025 add_compile_fail_case("@typeOf number literal", R"SOURCE(
1026const x = 3;1026const x = 3;
1027struct Foo {1027struct Foo {
1028 index: @typeof(x),1028 index: @typeOf(x),
1029}1029}
1030 )SOURCE", 1, ".tmp_source.zig:4:20: error: type '(integer literal)' not eligible for @typeof");1030 )SOURCE", 1, ".tmp_source.zig:4:20: error: type '(integer literal)' not eligible for @typeOf");
10311031
1032 add_compile_fail_case("integer overflow error", R"SOURCE(1032 add_compile_fail_case("integer overflow error", R"SOURCE(
1033const x : u8 = 300;1033const x : u8 = 300;
...@@ -1050,7 +1050,7 @@ struct Foo {...@@ -1050,7 +1050,7 @@ struct Foo {
1050 }1050 }
1051}1051}
10521052
1053const member_fn_type = @typeof(Foo.member_a);1053const member_fn_type = @typeOf(Foo.member_a);
1054const members = []member_fn_type {1054const members = []member_fn_type {
1055 Foo.member_a,1055 Foo.member_a,
1056 Foo.member_b,1056 Foo.member_b,
...@@ -1101,15 +1101,15 @@ fn func() -> bogus {}...@@ -1101,15 +1101,15 @@ fn func() -> bogus {}
11011101
11021102
1103 add_compile_fail_case("bogus compile var", R"SOURCE(1103 add_compile_fail_case("bogus compile var", R"SOURCE(
1104const x = @compile_var("bogus");1104const x = @compileVar("bogus");
1105 )SOURCE", 1, ".tmp_source.zig:2:24: error: unrecognized compile variable: 'bogus'");1105 )SOURCE", 1, ".tmp_source.zig:2:23: error: unrecognized compile variable: 'bogus'");
11061106
11071107
1108 add_compile_fail_case("@const_eval", R"SOURCE(1108 add_compile_fail_case("@constEval", R"SOURCE(
1109fn a(x: i32) {1109fn a(x: i32) {
1110 const y = @const_eval(x);1110 const y = @constEval(x);
1111}1111}
1112 )SOURCE", 1, ".tmp_source.zig:3:27: error: unable to evaluate constant expression");1112 )SOURCE", 1, ".tmp_source.zig:3:26: error: unable to evaluate constant expression");
11131113
1114 add_compile_fail_case("non constant expression in array size outside function", R"SOURCE(1114 add_compile_fail_case("non constant expression in array size outside function", R"SOURCE(
1115struct Foo {1115struct Foo {
...@@ -1245,8 +1245,8 @@ fn fibbonaci(x: i32) -> i32 {...@@ -1245,8 +1245,8 @@ fn fibbonaci(x: i32) -> i32 {
1245 ".tmp_source.zig:2:37: note: called from here",1245 ".tmp_source.zig:2:37: note: called from here",
1246 ".tmp_source.zig:4:40: note: quota exceeded here");1246 ".tmp_source.zig:4:40: note: quota exceeded here");
12471247
1248 add_compile_fail_case("@embed_file with bogus file", R"SOURCE(1248 add_compile_fail_case("@embedFile with bogus file", R"SOURCE(
1249const resource = @embed_file("bogus.txt");1249const resource = @embedFile("bogus.txt");
1250 )SOURCE", 1, ".tmp_source.zig:2:18: error: unable to find './bogus.txt'");1250 )SOURCE", 1, ".tmp_source.zig:2:18: error: unable to find './bogus.txt'");
12511251
12521252
...@@ -1555,23 +1555,23 @@ fn div0(a: i32, b: i32) -> i32 {...@@ -1555,23 +1555,23 @@ fn div0(a: i32, b: i32) -> i32 {
1555 add_debug_safety_case("exact division failure", R"SOURCE(1555 add_debug_safety_case("exact division failure", R"SOURCE(
1556error Whatever;1556error Whatever;
1557pub fn main(args: [][]u8) -> %void {1557pub fn main(args: [][]u8) -> %void {
1558 const x = div_exact(10, 3);1558 const x = divExact(10, 3);
1559 if (x == 0) return error.Whatever;1559 if (x == 0) return error.Whatever;
1560}1560}
1561#static_eval_enable(false)1561#static_eval_enable(false)
1562fn div_exact(a: i32, b: i32) -> i32 {1562fn divExact(a: i32, b: i32) -> i32 {
1563 @div_exact(a, b)1563 @divExact(a, b)
1564}1564}
1565 )SOURCE");1565 )SOURCE");
15661566
1567 add_debug_safety_case("cast []u8 to bigger slice of wrong size", R"SOURCE(1567 add_debug_safety_case("cast []u8 to bigger slice of wrong size", R"SOURCE(
1568error Whatever;1568error Whatever;
1569pub fn main(args: [][]u8) -> %void {1569pub fn main(args: [][]u8) -> %void {
1570 const x = widen_slice([]u8{1, 2, 3, 4, 5});1570 const x = widenSlice([]u8{1, 2, 3, 4, 5});
1571 if (x.len == 0) return error.Whatever;1571 if (x.len == 0) return error.Whatever;
1572}1572}
1573#static_eval_enable(false)1573#static_eval_enable(false)
1574fn widen_slice(slice: []u8) -> []i32 {1574fn widenSlice(slice: []u8) -> []i32 {
1575 ([]i32)(slice)1575 ([]i32)(slice)
1576}1576}
1577 )SOURCE");1577 )SOURCE");
test/self_hosted.zig+357-364
...@@ -3,29 +3,30 @@ const assert = std.debug.assert;...@@ -3,29 +3,30 @@ const assert = std.debug.assert;
3const str = std.str;3const str = std.str;
4const cstr = std.cstr;4const cstr = std.cstr;
5const other = @import("other.zig");5const other = @import("other.zig");
6const cases_return_type_type = @import("cases/return_type_type.zig");6const test_return_type_type = @import("cases/return_type_type.zig");
7const test_zeroes = @import("cases/zeroes.zig");7const test_zeroes = @import("cases/zeroes.zig");
8const test_sizeof_and_typeof = @import("cases/sizeof_and_typeof.zig");
89
9// normal comment10// normal comment
10/// this is a documentation comment11/// this is a documentation comment
11/// doc comment line 212/// doc comment line 2
12#attribute("test")13#attribute("test")
13fn empty_function_with_comments() {}14fn emptyFunctionWithComments() {}
1415
1516
16#attribute("test")17#attribute("test")
17fn if_statements() {18fn ifStatements() {
18 should_be_equal(1, 1);19 shouldBeEqual(1, 1);
19 first_eql_third(2, 1, 2);20 firstEqlThird(2, 1, 2);
20}21}
21fn should_be_equal(a: i32, b: i32) {22fn shouldBeEqual(a: i32, b: i32) {
22 if (a != b) {23 if (a != b) {
23 unreachable{};24 unreachable{};
24 } else {25 } else {
25 return;26 return;
26 }27 }
27}28}
28fn first_eql_third(a: i32, b: i32, c: i32) {29fn firstEqlThird(a: i32, b: i32, c: i32) {
29 if (a == b) {30 if (a == b) {
30 unreachable{};31 unreachable{};
31 } else if (b == c) {32 } else if (b == c) {
...@@ -40,33 +41,33 @@ fn first_eql_third(a: i32, b: i32, c: i32) {...@@ -40,33 +41,33 @@ fn first_eql_third(a: i32, b: i32, c: i32) {
4041
41#attribute("test")42#attribute("test")
42fn params() {43fn params() {
43 assert(test_params_add(22, 11) == 33);44 assert(testParamsAdd(22, 11) == 33);
44}45}
45fn test_params_add(a: i32, b: i32) -> i32 {46fn testParamsAdd(a: i32, b: i32) -> i32 {
46 a + b47 a + b
47}48}
4849
4950
50#attribute("test")51#attribute("test")
51fn local_variables() {52fn localVariables() {
52 test_loc_vars(2);53 testLocVars(2);
53}54}
54fn test_loc_vars(b: i32) {55fn testLocVars(b: i32) {
55 const a: i32 = 1;56 const a: i32 = 1;
56 if (a + b != 3) unreachable{};57 if (a + b != 3) unreachable{};
57}58}
5859
59#attribute("test")60#attribute("test")
60fn bool_literals() {61fn boolLiterals() {
61 assert(true);62 assert(true);
62 assert(!false);63 assert(!false);
63}64}
6465
65#attribute("test")66#attribute("test")
66fn void_parameters() {67fn voidParameters() {
67 void_fun(1, void{}, 2, {});68 voidFun(1, void{}, 2, {});
68}69}
69fn void_fun(a : i32, b : void, c : i32, d : void) {70fn voidFun(a : i32, b : void, c : i32, d : void) {
70 const v = b;71 const v = b;
71 const vv : void = if (a == 1) {v} else {};72 const vv : void = if (a == 1) {v} else {};
72 assert(a + c == 3);73 assert(a + c == 3);
...@@ -74,7 +75,7 @@ fn void_fun(a : i32, b : void, c : i32, d : void) {...@@ -74,7 +75,7 @@ fn void_fun(a : i32, b : void, c : i32, d : void) {
74}75}
7576
76#attribute("test")77#attribute("test")
77fn mutable_local_variables() {78fn mutableLocalVariables() {
78 var zero : i32 = 0;79 var zero : i32 = 0;
79 assert(zero == 0);80 assert(zero == 0);
8081
...@@ -104,31 +105,31 @@ fn arrays() {...@@ -104,31 +105,31 @@ fn arrays() {
104 }105 }
105106
106 assert(accumulator == 15);107 assert(accumulator == 15);
107 assert(get_array_len(array) == 5);108 assert(getArrayLen(array) == 5);
108}109}
109fn get_array_len(a: []u32) -> usize {110fn getArrayLen(a: []u32) -> usize {
110 a.len111 a.len
111}112}
112113
113#attribute("test")114#attribute("test")
114fn short_circuit() {115fn shortCircuit() {
115 var hit_1 = false;116 var hit_1 = false;
116 var hit_2 = false;117 var hit_2 = false;
117 var hit_3 = false;118 var hit_3 = false;
118 var hit_4 = false;119 var hit_4 = false;
119120
120 if (true || {assert_runtime(false); false}) {121 if (true || {assertRuntime(false); false}) {
121 hit_1 = true;122 hit_1 = true;
122 }123 }
123 if (false || { hit_2 = true; false }) {124 if (false || { hit_2 = true; false }) {
124 assert_runtime(false);125 assertRuntime(false);
125 }126 }
126127
127 if (true && { hit_3 = true; false }) {128 if (true && { hit_3 = true; false }) {
128 assert_runtime(false);129 assertRuntime(false);
129 }130 }
130 if (false && {assert_runtime(false); false}) {131 if (false && {assertRuntime(false); false}) {
131 assert_runtime(false);132 assertRuntime(false);
132 } else {133 } else {
133 hit_4 = true;134 hit_4 = true;
134 }135 }
...@@ -139,12 +140,12 @@ fn short_circuit() {...@@ -139,12 +140,12 @@ fn short_circuit() {
139}140}
140141
141#static_eval_enable(false)142#static_eval_enable(false)
142fn assert_runtime(b: bool) {143fn assertRuntime(b: bool) {
143 if (!b) unreachable{}144 if (!b) unreachable{}
144}145}
145146
146#attribute("test")147#attribute("test")
147fn modify_operators() {148fn modifyOperators() {
148 var i : i32 = 0;149 var i : i32 = 0;
149 i += 5; assert(i == 5);150 i += 5; assert(i == 5);
150 i -= 2; assert(i == 3);151 i -= 2; assert(i == 3);
...@@ -162,7 +163,7 @@ fn modify_operators() {...@@ -162,7 +163,7 @@ fn modify_operators() {
162163
163164
164#attribute("test")165#attribute("test")
165fn separate_block_scopes() {166fn separateBlockScopes() {
166 {167 {
167 const no_conflict : i32 = 5;168 const no_conflict : i32 = 5;
168 assert(no_conflict == 5);169 assert(no_conflict == 5);
...@@ -177,14 +178,14 @@ fn separate_block_scopes() {...@@ -177,14 +178,14 @@ fn separate_block_scopes() {
177178
178179
179#attribute("test")180#attribute("test")
180fn void_struct_fields() {181fn voidStructFields() {
181 const foo = VoidStructFieldsFoo {182 const foo = VoidStructFieldsFoo {
182 .a = void{},183 .a = void{},
183 .b = 1,184 .b = 1,
184 .c = void{},185 .c = void{},
185 };186 };
186 assert(foo.b == 1);187 assert(foo.b == 1);
187 assert(@sizeof(VoidStructFieldsFoo) == 4);188 assert(@sizeOf(VoidStructFieldsFoo) == 4);
188}189}
189struct VoidStructFieldsFoo {190struct VoidStructFieldsFoo {
190 a : void,191 a : void,
...@@ -197,11 +198,11 @@ struct VoidStructFieldsFoo {...@@ -197,11 +198,11 @@ struct VoidStructFieldsFoo {
197#attribute("test")198#attribute("test")
198pub fn structs() {199pub fn structs() {
199 var foo : StructFoo = undefined;200 var foo : StructFoo = undefined;
200 @memset(&foo, 0, @sizeof(StructFoo));201 @memset(&foo, 0, @sizeOf(StructFoo));
201 foo.a += 1;202 foo.a += 1;
202 foo.b = foo.a == 1;203 foo.b = foo.a == 1;
203 test_foo(foo);204 testFoo(foo);
204 test_mutation(&foo);205 testMutation(&foo);
205 assert(foo.c == 100);206 assert(foo.c == 100);
206}207}
207struct StructFoo {208struct StructFoo {
...@@ -209,10 +210,10 @@ struct StructFoo {...@@ -209,10 +210,10 @@ struct StructFoo {
209 b : bool,210 b : bool,
210 c : f32,211 c : f32,
211}212}
212fn test_foo(foo : StructFoo) {213fn testFoo(foo : StructFoo) {
213 assert(foo.b);214 assert(foo.b);
214}215}
215fn test_mutation(foo : &StructFoo) {216fn testMutation(foo : &StructFoo) {
216 foo.c = 100;217 foo.c = 100;
217}218}
218struct Node {219struct Node {
...@@ -225,7 +226,7 @@ struct Val {...@@ -225,7 +226,7 @@ struct Val {
225}226}
226227
227#attribute("test")228#attribute("test")
228fn struct_point_to_self() {229fn structPointToSelf() {
229 var root : Node = undefined;230 var root : Node = undefined;
230 root.val.x = 1;231 root.val.x = 1;
231232
...@@ -239,7 +240,7 @@ fn struct_point_to_self() {...@@ -239,7 +240,7 @@ fn struct_point_to_self() {
239}240}
240241
241#attribute("test")242#attribute("test")
242fn struct_byval_assign() {243fn structByvalAssign() {
243 var foo1 : StructFoo = undefined;244 var foo1 : StructFoo = undefined;
244 var foo2 : StructFoo = undefined;245 var foo2 : StructFoo = undefined;
245246
...@@ -250,7 +251,7 @@ fn struct_byval_assign() {...@@ -250,7 +251,7 @@ fn struct_byval_assign() {
250 assert(foo2.a == 1234);251 assert(foo2.a == 1234);
251}252}
252253
253fn struct_initializer() {254fn structInitializer() {
254 const val = Val { .x = 42 };255 const val = Val { .x = 42 };
255 assert(val.x == 42);256 assert(val.x == 42);
256}257}
...@@ -260,7 +261,7 @@ const g1 : i32 = 1233 + 1;...@@ -260,7 +261,7 @@ const g1 : i32 = 1233 + 1;
260var g2 : i32 = 0;261var g2 : i32 = 0;
261262
262#attribute("test")263#attribute("test")
263fn global_variables() {264fn globalVariables() {
264 assert(g2 == 0);265 assert(g2 == 0);
265 g2 = g1;266 g2 = g1;
266 assert(g2 == 1234);267 assert(g2 == 1234);
...@@ -268,55 +269,55 @@ fn global_variables() {...@@ -268,55 +269,55 @@ fn global_variables() {
268269
269270
270#attribute("test")271#attribute("test")
271fn while_loop() {272fn whileLoop() {
272 var i : i32 = 0;273 var i : i32 = 0;
273 while (i < 4) {274 while (i < 4) {
274 i += 1;275 i += 1;
275 }276 }
276 assert(i == 4);277 assert(i == 4);
277 assert(while_loop_1() == 1);278 assert(whileLoop1() == 1);
278}279}
279fn while_loop_1() -> i32 {280fn whileLoop1() -> i32 {
280 return while_loop_2();281 return whileLoop2();
281}282}
282fn while_loop_2() -> i32 {283fn whileLoop2() -> i32 {
283 while (true) {284 while (true) {
284 return 1;285 return 1;
285 }286 }
286}287}
287288
288#attribute("test")289#attribute("test")
289fn void_arrays() {290fn voidArrays() {
290 var array: [4]void = undefined;291 var array: [4]void = undefined;
291 array[0] = void{};292 array[0] = void{};
292 array[1] = array[2];293 array[1] = array[2];
293 assert(@sizeof(@typeof(array)) == 0);294 assert(@sizeOf(@typeOf(array)) == 0);
294 assert(array.len == 4);295 assert(array.len == 4);
295}296}
296297
297298
298#attribute("test")299#attribute("test")
299fn three_expr_in_a_row() {300fn threeExprInARow() {
300 assert_false(false || false || false);301 assertFalse(false || false || false);
301 assert_false(true && true && false);302 assertFalse(true && true && false);
302 assert_false(1 | 2 | 4 != 7);303 assertFalse(1 | 2 | 4 != 7);
303 assert_false(3 ^ 6 ^ 8 != 13);304 assertFalse(3 ^ 6 ^ 8 != 13);
304 assert_false(7 & 14 & 28 != 4);305 assertFalse(7 & 14 & 28 != 4);
305 assert_false(9 << 1 << 2 != 9 << 3);306 assertFalse(9 << 1 << 2 != 9 << 3);
306 assert_false(90 >> 1 >> 2 != 90 >> 3);307 assertFalse(90 >> 1 >> 2 != 90 >> 3);
307 assert_false(100 - 1 + 1000 != 1099);308 assertFalse(100 - 1 + 1000 != 1099);
308 assert_false(5 * 4 / 2 % 3 != 1);309 assertFalse(5 * 4 / 2 % 3 != 1);
309 assert_false(i32(i32(5)) != 5);310 assertFalse(i32(i32(5)) != 5);
310 assert_false(!!false);311 assertFalse(!!false);
311 assert_false(i32(7) != --(i32(7)));312 assertFalse(i32(7) != --(i32(7)));
312}313}
313fn assert_false(b: bool) {314fn assertFalse(b: bool) {
314 assert(!b);315 assert(!b);
315}316}
316317
317318
318#attribute("test")319#attribute("test")
319fn maybe_type() {320fn maybeType() {
320 const x : ?bool = true;321 const x : ?bool = true;
321322
322 if (const y ?= x) {323 if (const y ?= x) {
...@@ -344,21 +345,21 @@ fn maybe_type() {...@@ -344,21 +345,21 @@ fn maybe_type() {
344345
345346
346#attribute("test")347#attribute("test")
347fn enum_type() {348fn enumType() {
348 const foo1 = EnumTypeFoo.One {13};349 const foo1 = EnumTypeFoo.One {13};
349 const foo2 = EnumTypeFoo.Two {EnumType { .x = 1234, .y = 5678, }};350 const foo2 = EnumTypeFoo.Two {EnumType { .x = 1234, .y = 5678, }};
350 const bar = EnumTypeBar.B;351 const bar = EnumTypeBar.B;
351352
352 assert(bar == EnumTypeBar.B);353 assert(bar == EnumTypeBar.B);
353 assert(@member_count(EnumTypeFoo) == 3);354 assert(@memberCount(EnumTypeFoo) == 3);
354 assert(@member_count(EnumTypeBar) == 4);355 assert(@memberCount(EnumTypeBar) == 4);
355 const expected_foo_size = switch (@compile_var("arch")) {356 const expected_foo_size = switch (@compileVar("arch")) {
356 i386 => 20,357 i386 => 20,
357 x86_64 => 24,358 x86_64 => 24,
358 else => unreachable{},359 else => unreachable{},
359 };360 };
360 assert(@sizeof(EnumTypeFoo) == expected_foo_size);361 assert(@sizeOf(EnumTypeFoo) == expected_foo_size);
361 assert(@sizeof(EnumTypeBar) == 1);362 assert(@sizeOf(EnumTypeBar) == 1);
362}363}
363struct EnumType {364struct EnumType {
364 x: u64,365 x: u64,
...@@ -378,16 +379,16 @@ enum EnumTypeBar {...@@ -378,16 +379,16 @@ enum EnumTypeBar {
378379
379380
380#attribute("test")381#attribute("test")
381fn array_literal() {382fn arrayLiteral() {
382 const HEX_MULT = []u16{4096, 256, 16, 1};383 const hex_mult = []u16{4096, 256, 16, 1};
383384
384 assert(HEX_MULT.len == 4);385 assert(hex_mult.len == 4);
385 assert(HEX_MULT[1] == 256);386 assert(hex_mult[1] == 256);
386}387}
387388
388389
389#attribute("test")390#attribute("test")
390fn const_number_literal() {391fn constNumberLiteral() {
391 const one = 1;392 const one = 1;
392 const eleven = ten + one;393 const eleven = ten + one;
393394
...@@ -397,7 +398,7 @@ const ten = 10;...@@ -397,7 +398,7 @@ const ten = 10;
397398
398399
399#attribute("test")400#attribute("test")
400fn error_values() {401fn errorValues() {
401 const a = i32(error.err1);402 const a = i32(error.err1);
402 const b = i32(error.err2);403 const b = i32(error.err2);
403 assert(a != b);404 assert(a != b);
...@@ -408,30 +409,30 @@ error err2;...@@ -408,30 +409,30 @@ error err2;
408409
409410
410#attribute("test")411#attribute("test")
411fn fn_call_of_struct_field() {412fn fnCallOfStructField() {
412 assert(call_struct_field(Foo {.ptr = a_func,}) == 13);413 assert(callStructField(Foo {.ptr = aFunc,}) == 13);
413}414}
414415
415struct Foo {416struct Foo {
416 ptr: fn() -> i32,417 ptr: fn() -> i32,
417}418}
418419
419fn a_func() -> i32 { 13 }420fn aFunc() -> i32 { 13 }
420421
421fn call_struct_field(foo: Foo) -> i32 {422fn callStructField(foo: Foo) -> i32 {
422 return foo.ptr();423 return foo.ptr();
423}424}
424425
425426
426427
427#attribute("test")428#attribute("test")
428fn redefinition_of_error_values_allowed() {429fn redefinitionOfErrorValuesAllowed() {
429 should_be_not_equal(error.AnError, error.SecondError);430 shouldBeNotEqual(error.AnError, error.SecondError);
430}431}
431error AnError;432error AnError;
432error AnError;433error AnError;
433error SecondError;434error SecondError;
434fn should_be_not_equal(a: error, b: error) {435fn shouldBeNotEqual(a: error, b: error) {
435 if (a == b) unreachable{}436 if (a == b) unreachable{}
436}437}
437438
...@@ -439,21 +440,21 @@ fn should_be_not_equal(a: error, b: error) {...@@ -439,21 +440,21 @@ fn should_be_not_equal(a: error, b: error) {
439440
440441
441#attribute("test")442#attribute("test")
442fn constant_enum_with_payload() {443fn constantEnumWithPayload() {
443 var empty = AnEnumWithPayload.Empty;444 var empty = AnEnumWithPayload.Empty;
444 var full = AnEnumWithPayload.Full {13};445 var full = AnEnumWithPayload.Full {13};
445 should_be_empty(empty);446 shouldBeEmpty(empty);
446 should_be_not_empty(full);447 shouldBeNotEmpty(full);
447}448}
448449
449fn should_be_empty(x: AnEnumWithPayload) {450fn shouldBeEmpty(x: AnEnumWithPayload) {
450 switch (x) {451 switch (x) {
451 Empty => {},452 Empty => {},
452 else => unreachable{},453 else => unreachable{},
453 }454 }
454}455}
455456
456fn should_be_not_empty(x: AnEnumWithPayload) {457fn shouldBeNotEmpty(x: AnEnumWithPayload) {
457 switch (x) {458 switch (x) {
458 Empty => unreachable{},459 Empty => unreachable{},
459 else => {},460 else => {},
...@@ -467,7 +468,7 @@ enum AnEnumWithPayload {...@@ -467,7 +468,7 @@ enum AnEnumWithPayload {
467468
468469
469#attribute("test")470#attribute("test")
470fn continue_in_for_loop() {471fn continueInForLoop() {
471 const array = []i32 {1, 2, 3, 4, 5};472 const array = []i32 {1, 2, 3, 4, 5};
472 var sum : i32 = 0;473 var sum : i32 = 0;
473 for (array) |x| {474 for (array) |x| {
...@@ -482,24 +483,24 @@ fn continue_in_for_loop() {...@@ -482,24 +483,24 @@ fn continue_in_for_loop() {
482483
483484
484#attribute("test")485#attribute("test")
485fn cast_bool_to_int() {486fn castBoolToInt() {
486 const t = true;487 const t = true;
487 const f = false;488 const f = false;
488 assert(i32(t) == i32(1));489 assert(i32(t) == i32(1));
489 assert(i32(f) == i32(0));490 assert(i32(f) == i32(0));
490 non_const_cast_bool_to_int(t, f);491 nonConstCastBoolToInt(t, f);
491}492}
492493
493fn non_const_cast_bool_to_int(t: bool, f: bool) {494fn nonConstCastBoolToInt(t: bool, f: bool) {
494 assert(i32(t) == i32(1));495 assert(i32(t) == i32(1));
495 assert(i32(f) == i32(0));496 assert(i32(f) == i32(0));
496}497}
497498
498499
499#attribute("test")500#attribute("test")
500fn switch_on_enum() {501fn switchOnEnum() {
501 const fruit = Fruit.Orange;502 const fruit = Fruit.Orange;
502 non_const_switch_on_enum(fruit);503 nonConstSwitchOnEnum(fruit);
503}504}
504enum Fruit {505enum Fruit {
505 Apple,506 Apple,
...@@ -507,7 +508,7 @@ enum Fruit {...@@ -507,7 +508,7 @@ enum Fruit {
507 Banana,508 Banana,
508}509}
509#static_eval_enable(false)510#static_eval_enable(false)
510fn non_const_switch_on_enum(fruit: Fruit) {511fn nonConstSwitchOnEnum(fruit: Fruit) {
511 switch (fruit) {512 switch (fruit) {
512 Apple => unreachable{},513 Apple => unreachable{},
513 Orange => {},514 Orange => {},
...@@ -516,11 +517,11 @@ fn non_const_switch_on_enum(fruit: Fruit) {...@@ -516,11 +517,11 @@ fn non_const_switch_on_enum(fruit: Fruit) {
516}517}
517518
518#attribute("test")519#attribute("test")
519fn switch_statement() {520fn switchStatement() {
520 non_const_switch(SwitchStatmentFoo.C);521 nonConstSwitch(SwitchStatmentFoo.C);
521}522}
522#static_eval_enable(false)523#static_eval_enable(false)
523fn non_const_switch(foo: SwitchStatmentFoo) {524fn nonConstSwitch(foo: SwitchStatmentFoo) {
524 const val: i32 = switch (foo) {525 const val: i32 = switch (foo) {
525 A => 1,526 A => 1,
526 B => 2,527 B => 2,
...@@ -538,10 +539,10 @@ enum SwitchStatmentFoo {...@@ -538,10 +539,10 @@ enum SwitchStatmentFoo {
538539
539540
540#attribute("test")541#attribute("test")
541fn switch_prong_with_var() {542fn switchProngWithVar() {
542 switch_prong_with_var_fn(SwitchProngWithVarEnum.One {13});543 switchProngWithVarFn(SwitchProngWithVarEnum.One {13});
543 switch_prong_with_var_fn(SwitchProngWithVarEnum.Two {13.0});544 switchProngWithVarFn(SwitchProngWithVarEnum.Two {13.0});
544 switch_prong_with_var_fn(SwitchProngWithVarEnum.Meh);545 switchProngWithVarFn(SwitchProngWithVarEnum.Meh);
545}546}
546enum SwitchProngWithVarEnum {547enum SwitchProngWithVarEnum {
547 One: i32,548 One: i32,
...@@ -549,7 +550,7 @@ enum SwitchProngWithVarEnum {...@@ -549,7 +550,7 @@ enum SwitchProngWithVarEnum {
549 Meh,550 Meh,
550}551}
551#static_eval_enable(false)552#static_eval_enable(false)
552fn switch_prong_with_var_fn(a: SwitchProngWithVarEnum) {553fn switchProngWithVarFn(a: SwitchProngWithVarEnum) {
553 switch(a) {554 switch(a) {
554 One => |x| {555 One => |x| {
555 if (x != 13) unreachable{};556 if (x != 13) unreachable{};
...@@ -565,54 +566,54 @@ fn switch_prong_with_var_fn(a: SwitchProngWithVarEnum) {...@@ -565,54 +566,54 @@ fn switch_prong_with_var_fn(a: SwitchProngWithVarEnum) {
565566
566567
567#attribute("test")568#attribute("test")
568fn err_return_in_assignment() {569fn errReturnInAssignment() {
569 %%do_err_return_in_assignment();570 %%doErrReturnInAssignment();
570}571}
571572
572#static_eval_enable(false)573#static_eval_enable(false)
573fn do_err_return_in_assignment() -> %void {574fn doErrReturnInAssignment() -> %void {
574 var x : i32 = undefined;575 var x : i32 = undefined;
575 x = %return make_a_non_err();576 x = %return makeANonErr();
576}577}
577578
578fn make_a_non_err() -> %i32 {579fn makeANonErr() -> %i32 {
579 return 1;580 return 1;
580}581}
581582
582583
583584
584#attribute("test")585#attribute("test")
585fn rhs_maybe_unwrap_return() {586fn rhsMaybeUnwrapReturn() {
586 const x = ?true;587 const x = ?true;
587 const y = x ?? return;588 const y = x ?? return;
588}589}
589590
590591
591#attribute("test")592#attribute("test")
592fn implicit_cast_fn_unreachable_return() {593fn implicitCastFnUnreachableReturn() {
593 wants_fn_with_void(fn_with_unreachable);594 wantsFnWithVoid(fnWithUnreachable);
594}595}
595596
596fn wants_fn_with_void(f: fn()) { }597fn wantsFnWithVoid(f: fn()) { }
597598
598fn fn_with_unreachable() -> unreachable {599fn fnWithUnreachable() -> unreachable {
599 unreachable {}600 unreachable {}
600}601}
601602
602603
603#attribute("test")604#attribute("test")
604fn explicit_cast_maybe_pointers() {605fn explicitCastMaybePointers() {
605 const a: ?&i32 = undefined;606 const a: ?&i32 = undefined;
606 const b: ?&f32 = (?&f32)(a);607 const b: ?&f32 = (?&f32)(a);
607}608}
608609
609610
610#attribute("test")611#attribute("test")
611fn const_expr_eval_on_single_expr_blocks() {612fn constExprEvalOnSingleExprBlocks() {
612 assert(const_expr_eval_on_single_expr_blocks_fn(1, true) == 3);613 assert(constExprEvalOnSingleExprBlocksFn(1, true) == 3);
613}614}
614615
615fn const_expr_eval_on_single_expr_blocks_fn(x: i32, b: bool) -> i32 {616fn constExprEvalOnSingleExprBlocksFn(x: i32, b: bool) -> i32 {
616 const literal = 3;617 const literal = 3;
617618
618 const result = if (b) {619 const result = if (b) {
...@@ -626,9 +627,9 @@ fn const_expr_eval_on_single_expr_blocks_fn(x: i32, b: bool) -> i32 {...@@ -626,9 +627,9 @@ fn const_expr_eval_on_single_expr_blocks_fn(x: i32, b: bool) -> i32 {
626627
627628
628#attribute("test")629#attribute("test")
629fn builtin_const_eval() {630fn builtinConstEval() {
630 const x : i32 = @const_eval(1 + 2 + 3);631 const x : i32 = @constEval(1 + 2 + 3);
631 assert(x == @const_eval(6));632 assert(x == @constEval(6));
632}633}
633634
634#attribute("test")635#attribute("test")
...@@ -650,7 +651,7 @@ fn slicing() {...@@ -650,7 +651,7 @@ fn slicing() {
650651
651652
652#attribute("test")653#attribute("test")
653fn memcpy_and_memset_intrinsics() {654fn memcpyAndMemsetIntrinsics() {
654 var foo : [20]u8 = undefined;655 var foo : [20]u8 = undefined;
655 var bar : [20]u8 = undefined;656 var bar : [20]u8 = undefined;
656657
...@@ -662,22 +663,22 @@ fn memcpy_and_memset_intrinsics() {...@@ -662,22 +663,22 @@ fn memcpy_and_memset_intrinsics() {
662663
663664
664#attribute("test")665#attribute("test")
665fn array_dot_len_const_expr() { }666fn arrayDotLenConstExpr() { }
666struct ArrayDotLenConstExpr {667struct ArrayDotLenConstExpr {
667 y: [@const_eval(some_array.len)]u8,668 y: [@constEval(some_array.len)]u8,
668}669}
669const some_array = []u8 {0, 1, 2, 3};670const some_array = []u8 {0, 1, 2, 3};
670671
671672
672#attribute("test")673#attribute("test")
673fn count_leading_zeroes() {674fn countLeadingZeroes() {
674 assert(@clz(u8, 0b00001010) == 4);675 assert(@clz(u8, 0b00001010) == 4);
675 assert(@clz(u8, 0b10001010) == 0);676 assert(@clz(u8, 0b10001010) == 0);
676 assert(@clz(u8, 0b00000000) == 8);677 assert(@clz(u8, 0b00000000) == 8);
677}678}
678679
679#attribute("test")680#attribute("test")
680fn count_trailing_zeroes() {681fn countTrailingZeroes() {
681 assert(@ctz(u8, 0b10100000) == 5);682 assert(@ctz(u8, 0b10100000) == 5);
682 assert(@ctz(u8, 0b10001010) == 1);683 assert(@ctz(u8, 0b10001010) == 1);
683 assert(@ctz(u8, 0b00000000) == 8);684 assert(@ctz(u8, 0b00000000) == 8);
...@@ -685,7 +686,7 @@ fn count_trailing_zeroes() {...@@ -685,7 +686,7 @@ fn count_trailing_zeroes() {
685686
686687
687#attribute("test")688#attribute("test")
688fn multiline_string() {689fn multilineString() {
689 const s1 =690 const s1 =
690 \\one691 \\one
691 \\two)692 \\two)
...@@ -696,7 +697,7 @@ fn multiline_string() {...@@ -696,7 +697,7 @@ fn multiline_string() {
696}697}
697698
698#attribute("test")699#attribute("test")
699fn multiline_c_string() {700fn multilineCString() {
700 const s1 =701 const s1 =
701 c\\one702 c\\one
702 c\\two)703 c\\two)
...@@ -709,7 +710,7 @@ fn multiline_c_string() {...@@ -709,7 +710,7 @@ fn multiline_c_string() {
709710
710711
711#attribute("test")712#attribute("test")
712fn simple_generic_fn() {713fn simpleGenericFn() {
713 assert(max(i32, 3, -1) == 3);714 assert(max(i32, 3, -1) == 3);
714 assert(max(f32, 0.123, 0.456) == 0.456);715 assert(max(f32, 0.123, 0.456) == 0.456);
715 assert(add(2, 3) == 5);716 assert(add(2, 3) == 5);
...@@ -720,42 +721,42 @@ fn max(inline T: type, a: T, b: T) -> T {...@@ -720,42 +721,42 @@ fn max(inline T: type, a: T, b: T) -> T {
720}721}
721722
722fn add(inline a: i32, b: i32) -> i32 {723fn add(inline a: i32, b: i32) -> i32 {
723 return @const_eval(a) + b;724 return @constEval(a) + b;
724}725}
725726
726727
727#attribute("test")728#attribute("test")
728fn constant_equal_function_pointers() {729fn constantEqualFunctionPointers() {
729 const alias = empty_fn;730 const alias = emptyFn;
730 assert(@const_eval(empty_fn == alias));731 assert(@constEval(emptyFn == alias));
731}732}
732733
733fn empty_fn() {}734fn emptyFn() {}
734735
735736
736#attribute("test")737#attribute("test")
737fn generic_malloc_free() {738fn genericMallocFree() {
738 const a = %%mem_alloc(u8, 10);739 const a = %%memAlloc(u8, 10);
739 mem_free(u8, a);740 memFree(u8, a);
740}741}
741const some_mem : [100]u8 = undefined;742const some_mem : [100]u8 = undefined;
742#static_eval_enable(false)743#static_eval_enable(false)
743fn mem_alloc(inline T: type, n: usize) -> %[]T {744fn memAlloc(inline T: type, n: usize) -> %[]T {
744 return (&T)(&some_mem[0])[0...n];745 return (&T)(&some_mem[0])[0...n];
745}746}
746fn mem_free(inline T: type, mem: []T) { }747fn memFree(inline T: type, mem: []T) { }
747748
748749
749#attribute("test")750#attribute("test")
750fn call_fn_with_empty_string() {751fn callFnWithEmptyString() {
751 accepts_string("");752 acceptsString("");
752}753}
753754
754fn accepts_string(foo: []u8) { }755fn acceptsString(foo: []u8) { }
755756
756757
757#attribute("test")758#attribute("test")
758fn hex_escape() {759fn hexEscape() {
759 assert(str.eql("\x68\x65\x6c\x6c\x6f", "hello"));760 assert(str.eql("\x68\x65\x6c\x6c\x6f", "hello"));
760}761}
761762
...@@ -763,18 +764,18 @@ fn hex_escape() {...@@ -763,18 +764,18 @@ fn hex_escape() {
763error AnError;764error AnError;
764error ALongerErrorName;765error ALongerErrorName;
765#attribute("test")766#attribute("test")
766fn error_name_string() {767fn errorNameString() {
767 assert(str.eql(@err_name(error.AnError), "AnError"));768 assert(str.eql(@errName(error.AnError), "AnError"));
768 assert(str.eql(@err_name(error.ALongerErrorName), "ALongerErrorName"));769 assert(str.eql(@errName(error.ALongerErrorName), "ALongerErrorName"));
769}770}
770771
771772
772#attribute("test")773#attribute("test")
773fn goto_and_labels() {774fn gotoAndLabels() {
774 goto_loop();775 gotoLoop();
775 assert(goto_counter == 10);776 assert(goto_counter == 10);
776}777}
777fn goto_loop() {778fn gotoLoop() {
778 var i: i32 = 0;779 var i: i32 = 0;
779 goto cond;780 goto cond;
780loop:781loop:
...@@ -790,11 +791,11 @@ var goto_counter: i32 = 0;...@@ -790,11 +791,11 @@ var goto_counter: i32 = 0;
790791
791792
792#attribute("test")793#attribute("test")
793fn goto_leave_defer_scope() {794fn gotoLeaveDeferScope() {
794 test_goto_leave_defer_scope(true);795 testGotoLeaveDeferScope(true);
795}796}
796#static_eval_enable(false)797#static_eval_enable(false)
797fn test_goto_leave_defer_scope(b: bool) {798fn testGotoLeaveDeferScope(b: bool) {
798 var it_worked = false;799 var it_worked = false;
799800
800 goto entry;801 goto entry;
...@@ -810,25 +811,25 @@ entry:...@@ -810,25 +811,25 @@ entry:
810811
811812
812#attribute("test")813#attribute("test")
813fn cast_undefined() {814fn castUndefined() {
814 const array: [100]u8 = undefined;815 const array: [100]u8 = undefined;
815 const slice = ([]u8)(array);816 const slice = ([]u8)(array);
816 test_cast_undefined(slice);817 testCastUndefined(slice);
817}818}
818fn test_cast_undefined(x: []u8) {}819fn testCastUndefined(x: []u8) {}
819820
820821
821#attribute("test")822#attribute("test")
822fn cast_small_unsigned_to_larger_signed() {823fn castSmallUnsignedToLargerSigned() {
823 assert(cast_small_unsigned_to_larger_signed_1(200) == i16(200));824 assert(castSmallUnsignedToLargerSigned1(200) == i16(200));
824 assert(cast_small_unsigned_to_larger_signed_2(9999) == i64(9999));825 assert(castSmallUnsignedToLargerSigned2(9999) == i64(9999));
825}826}
826fn cast_small_unsigned_to_larger_signed_1(x: u8) -> i16 { x }827fn castSmallUnsignedToLargerSigned1(x: u8) -> i16 { x }
827fn cast_small_unsigned_to_larger_signed_2(x: u16) -> i64 { x }828fn castSmallUnsignedToLargerSigned2(x: u16) -> i64 { x }
828829
829830
830#attribute("test")831#attribute("test")
831fn implicit_cast_after_unreachable() {832fn implicitCastAfterUnreachable() {
832 assert(outer() == 1234);833 assert(outer() == 1234);
833}834}
834fn inner() -> i32 { 1234 }835fn inner() -> i32 { 1234 }
...@@ -838,10 +839,10 @@ fn outer() -> i64 {...@@ -838,10 +839,10 @@ fn outer() -> i64 {
838839
839840
840#attribute("test")841#attribute("test")
841fn else_if_expression() {842fn elseIfExpression() {
842 assert(else_if_expression_f(1) == 1);843 assert(elseIfExpressionF(1) == 1);
843}844}
844fn else_if_expression_f(c: u8) -> u8 {845fn elseIfExpressionF(c: u8) -> u8 {
845 if (c == 0) {846 if (c == 0) {
846 0847 0
847 } else if (c == 1) {848 } else if (c == 1) {
...@@ -852,14 +853,14 @@ fn else_if_expression_f(c: u8) -> u8 {...@@ -852,14 +853,14 @@ fn else_if_expression_f(c: u8) -> u8 {
852}853}
853854
854#attribute("test")855#attribute("test")
855fn err_binary_operator() {856fn errBinaryOperator() {
856 const a = err_binary_operator_g(true) %% 3;857 const a = errBinaryOperatorG(true) %% 3;
857 const b = err_binary_operator_g(false) %% 3;858 const b = errBinaryOperatorG(false) %% 3;
858 assert(a == 3);859 assert(a == 3);
859 assert(b == 10);860 assert(b == 10);
860}861}
861error ItBroke;862error ItBroke;
862fn err_binary_operator_g(x: bool) -> %isize {863fn errBinaryOperatorG(x: bool) -> %isize {
863 if (x) {864 if (x) {
864 error.ItBroke865 error.ItBroke
865 } else {866 } else {
...@@ -868,18 +869,18 @@ fn err_binary_operator_g(x: bool) -> %isize {...@@ -868,18 +869,18 @@ fn err_binary_operator_g(x: bool) -> %isize {
868}869}
869870
870#attribute("test")871#attribute("test")
871fn unwrap_simple_value_from_error() {872fn unwrapSimpleValueFromError() {
872 const i = %%unwrap_simple_value_from_error_do();873 const i = %%unwrapSimpleValueFromErrorDo();
873 assert(i == 13);874 assert(i == 13);
874}875}
875fn unwrap_simple_value_from_error_do() -> %isize { 13 }876fn unwrapSimpleValueFromErrorDo() -> %isize { 13 }
876877
877878
878#attribute("test")879#attribute("test")
879fn store_member_function_in_variable() {880fn storeMemberFunctionInVariable() {
880 const instance = MemberFnTestFoo { .x = 1234, };881 const instance = MemberFnTestFoo { .x = 1234, };
881 const member_fn = MemberFnTestFoo.member;882 const memberFn = MemberFnTestFoo.member;
882 const result = member_fn(instance);883 const result = memberFn(instance);
883 assert(result == 1234);884 assert(result == 1234);
884}885}
885struct MemberFnTestFoo {886struct MemberFnTestFoo {
...@@ -888,34 +889,34 @@ struct MemberFnTestFoo {...@@ -888,34 +889,34 @@ struct MemberFnTestFoo {
888}889}
889890
890#attribute("test")891#attribute("test")
891fn call_member_function_directly() {892fn callMemberFunctionDirectly() {
892 const instance = MemberFnTestFoo { .x = 1234, };893 const instance = MemberFnTestFoo { .x = 1234, };
893 const result = MemberFnTestFoo.member(instance);894 const result = MemberFnTestFoo.member(instance);
894 assert(result == 1234);895 assert(result == 1234);
895}896}
896897
897#attribute("test")898#attribute("test")
898fn member_functions() {899fn memberFunctions() {
899 const r = MemberFnRand {.seed = 1234};900 const r = MemberFnRand {.seed = 1234};
900 assert(r.get_seed() == 1234);901 assert(r.getSeed() == 1234);
901}902}
902struct MemberFnRand {903struct MemberFnRand {
903 seed: u32,904 seed: u32,
904 pub fn get_seed(r: MemberFnRand) -> u32 {905 pub fn getSeed(r: MemberFnRand) -> u32 {
905 r.seed906 r.seed
906 }907 }
907}908}
908909
909#attribute("test")910#attribute("test")
910fn static_function_evaluation() {911fn staticFunctionEvaluation() {
911 assert(statically_added_number == 3);912 assert(statically_added_number == 3);
912}913}
913const statically_added_number = static_add(1, 2);914const statically_added_number = staticAdd(1, 2);
914fn static_add(a: i32, b: i32) -> i32 { a + b }915fn staticAdd(a: i32, b: i32) -> i32 { a + b }
915916
916917
917#attribute("test")918#attribute("test")
918fn statically_initalized_list() {919fn staticallyInitalizedList() {
919 assert(static_point_list[0].x == 1);920 assert(static_point_list[0].x == 1);
920 assert(static_point_list[0].y == 2);921 assert(static_point_list[0].y == 2);
921 assert(static_point_list[1].x == 3);922 assert(static_point_list[1].x == 3);
...@@ -925,8 +926,8 @@ struct Point {...@@ -925,8 +926,8 @@ struct Point {
925 x: i32,926 x: i32,
926 y: i32,927 y: i32,
927}928}
928const static_point_list = []Point { make_point(1, 2), make_point(3, 4) };929const static_point_list = []Point { makePoint(1, 2), makePoint(3, 4) };
929fn make_point(x: i32, y: i32) -> Point {930fn makePoint(x: i32, y: i32) -> Point {
930 return Point {931 return Point {
931 .x = x,932 .x = x,
932 .y = y,933 .y = y,
...@@ -935,7 +936,7 @@ fn make_point(x: i32, y: i32) -> Point {...@@ -935,7 +936,7 @@ fn make_point(x: i32, y: i32) -> Point {
935936
936937
937#attribute("test")938#attribute("test")
938fn static_eval_recursive() {939fn staticEvalRecursive() {
939 assert(seventh_fib_number == 21);940 assert(seventh_fib_number == 21);
940}941}
941const seventh_fib_number = fibbonaci(7);942const seventh_fib_number = fibbonaci(7);
...@@ -945,21 +946,21 @@ fn fibbonaci(x: i32) -> i32 {...@@ -945,21 +946,21 @@ fn fibbonaci(x: i32) -> i32 {
945}946}
946947
947#attribute("test")948#attribute("test")
948fn static_eval_while() {949fn staticEvalWhile() {
949 assert(static_eval_while_number == 1);950 assert(static_eval_while_number == 1);
950}951}
951const static_eval_while_number = static_while_loop_1();952const static_eval_while_number = staticWhileLoop1();
952fn static_while_loop_1() -> i32 {953fn staticWhileLoop1() -> i32 {
953 return while_loop_2();954 return whileLoop2();
954}955}
955fn static_while_loop_2() -> i32 {956fn staticWhileLoop2() -> i32 {
956 while (true) {957 while (true) {
957 return 1;958 return 1;
958 }959 }
959}960}
960961
961#attribute("test")962#attribute("test")
962fn static_eval_list_init() {963fn staticEvalListInit() {
963 assert(static_vec3.data[2] == 1.0);964 assert(static_vec3.data[2] == 1.0);
964}965}
965const static_vec3 = vec3(0.0, 0.0, 1.0);966const static_vec3 = vec3(0.0, 0.0, 1.0);
...@@ -974,22 +975,22 @@ pub fn vec3(x: f32, y: f32, z: f32) -> Vec3 {...@@ -974,22 +975,22 @@ pub fn vec3(x: f32, y: f32, z: f32) -> Vec3 {
974975
975976
976#attribute("test")977#attribute("test")
977fn generic_fn_with_implicit_cast() {978fn genericFnWithImplicitCast() {
978 assert(get_first_byte(u8, []u8 {13}) == 13);979 assert(getFirstByte(u8, []u8 {13}) == 13);
979 assert(get_first_byte(u16, []u16 {0, 13}) == 0);980 assert(getFirstByte(u16, []u16 {0, 13}) == 0);
980}981}
981fn get_byte(ptr: ?&u8) -> u8 {*??ptr}982fn getByte(ptr: ?&u8) -> u8 {*??ptr}
982fn get_first_byte(inline T: type, mem: []T) -> u8 {983fn getFirstByte(inline T: type, mem: []T) -> u8 {
983 get_byte((&u8)(&mem[0]))984 getByte((&u8)(&mem[0]))
984}985}
985986
986#attribute("test")987#attribute("test")
987fn continue_and_break() {988fn continueAndBreak() {
988 run_continue_and_break_test();989 runContinueAndBreakTest();
989 assert(continue_and_break_counter == 8);990 assert(continue_and_break_counter == 8);
990}991}
991var continue_and_break_counter: i32 = 0;992var continue_and_break_counter: i32 = 0;
992fn run_continue_and_break_test() {993fn runContinueAndBreakTest() {
993 var i : i32 = 0;994 var i : i32 = 0;
994 while (true) {995 while (true) {
995 continue_and_break_counter += 2;996 continue_and_break_counter += 2;
...@@ -1002,17 +1003,9 @@ fn run_continue_and_break_test() {...@@ -1002,17 +1003,9 @@ fn run_continue_and_break_test() {
1002 assert(i == 4);1003 assert(i == 4);
1003}1004}
10041005
1005#attribute("test")
1006fn sizeof_and_typeof() {
1007 const y: @typeof(sizeof_and_typeof_x) = 120;
1008 assert(@sizeof(@typeof(y)) == 2);
1009}
1010const sizeof_and_typeof_x: u16 = 13;
1011const sizeof_and_typeof_z: @typeof(sizeof_and_typeof_x) = 19;
1012
10131006
1014#attribute("test")1007#attribute("test")
1015fn pointer_dereferencing() {1008fn pointerDereferencing() {
1016 var x = i32(3);1009 var x = i32(3);
1017 const y = &x;1010 const y = &x;
10181011
...@@ -1023,47 +1016,47 @@ fn pointer_dereferencing() {...@@ -1023,47 +1016,47 @@ fn pointer_dereferencing() {
1023}1016}
10241017
1025#attribute("test")1018#attribute("test")
1026fn constant_expressions() {1019fn constantExpressions() {
1027 var array : [ARRAY_SIZE]u8 = undefined;1020 var array : [array_size]u8 = undefined;
1028 assert(@sizeof(@typeof(array)) == 20);1021 assert(@sizeOf(@typeOf(array)) == 20);
1029}1022}
1030const ARRAY_SIZE : u8 = 20;1023const array_size : u8 = 20;
10311024
10321025
1033#attribute("test")1026#attribute("test")
1034fn min_value_and_max_value() {1027fn minValueAndMaxValue() {
1035 assert(@max_value(u8) == 255);1028 assert(@maxValue(u8) == 255);
1036 assert(@max_value(u16) == 65535);1029 assert(@maxValue(u16) == 65535);
1037 assert(@max_value(u32) == 4294967295);1030 assert(@maxValue(u32) == 4294967295);
1038 assert(@max_value(u64) == 18446744073709551615);1031 assert(@maxValue(u64) == 18446744073709551615);
10391032
1040 assert(@max_value(i8) == 127);1033 assert(@maxValue(i8) == 127);
1041 assert(@max_value(i16) == 32767);1034 assert(@maxValue(i16) == 32767);
1042 assert(@max_value(i32) == 2147483647);1035 assert(@maxValue(i32) == 2147483647);
1043 assert(@max_value(i64) == 9223372036854775807);1036 assert(@maxValue(i64) == 9223372036854775807);
10441037
1045 assert(@min_value(u8) == 0);1038 assert(@minValue(u8) == 0);
1046 assert(@min_value(u16) == 0);1039 assert(@minValue(u16) == 0);
1047 assert(@min_value(u32) == 0);1040 assert(@minValue(u32) == 0);
1048 assert(@min_value(u64) == 0);1041 assert(@minValue(u64) == 0);
10491042
1050 assert(@min_value(i8) == -128);1043 assert(@minValue(i8) == -128);
1051 assert(@min_value(i16) == -32768);1044 assert(@minValue(i16) == -32768);
1052 assert(@min_value(i32) == -2147483648);1045 assert(@minValue(i32) == -2147483648);
1053 assert(@min_value(i64) == -9223372036854775808);1046 assert(@minValue(i64) == -9223372036854775808);
1054}1047}
10551048
1056#attribute("test")1049#attribute("test")
1057fn overflow_intrinsics() {1050fn overflowIntrinsics() {
1058 var result: u8 = undefined;1051 var result: u8 = undefined;
1059 assert(@add_with_overflow(u8, 250, 100, &result));1052 assert(@addWithOverflow(u8, 250, 100, &result));
1060 assert(!@add_with_overflow(u8, 100, 150, &result));1053 assert(!@addWithOverflow(u8, 100, 150, &result));
1061 assert(result == 250);1054 assert(result == 250);
1062}1055}
10631056
10641057
1065#attribute("test")1058#attribute("test")
1066fn nested_arrays() {1059fn nestedArrays() {
1067 const array_of_strings = [][]u8 {"hello", "this", "is", "my", "thing"};1060 const array_of_strings = [][]u8 {"hello", "this", "is", "my", "thing"};
1068 for (array_of_strings) |s, i| {1061 for (array_of_strings) |s, i| {
1069 if (i == 0) assert(str.eql(s, "hello"));1062 if (i == 0) assert(str.eql(s, "hello"));
...@@ -1075,7 +1068,7 @@ fn nested_arrays() {...@@ -1075,7 +1068,7 @@ fn nested_arrays() {
1075}1068}
10761069
1077#attribute("test")1070#attribute("test")
1078fn int_to_ptr_cast() {1071fn intToPtrCast() {
1079 const x = isize(13);1072 const x = isize(13);
1080 const y = (&u8)(x);1073 const y = (&u8)(x);
1081 const z = usize(y);1074 const z = usize(y);
...@@ -1083,12 +1076,12 @@ fn int_to_ptr_cast() {...@@ -1083,12 +1076,12 @@ fn int_to_ptr_cast() {
1083}1076}
10841077
1085#attribute("test")1078#attribute("test")
1086fn string_concatenation() {1079fn stringConcatenation() {
1087 assert(str.eql("OK" ++ " IT " ++ "WORKED", "OK IT WORKED"));1080 assert(str.eql("OK" ++ " IT " ++ "WORKED", "OK IT WORKED"));
1088}1081}
10891082
1090#attribute("test")1083#attribute("test")
1091fn constant_struct_with_negation() {1084fn constantStructWithNegation() {
1092 assert(vertices[0].x == -0.6);1085 assert(vertices[0].x == -0.6);
1093}1086}
1094struct Vertex {1087struct Vertex {
...@@ -1106,25 +1099,25 @@ const vertices = []Vertex {...@@ -1106,25 +1099,25 @@ const vertices = []Vertex {
11061099
11071100
1108#attribute("test")1101#attribute("test")
1109fn return_with_implicit_cast_from_while_loop() {1102fn returnWithImplicitCastFromWhileLoop() {
1110 %%return_with_implicit_cast_from_while_loop_test();1103 %%returnWithImplicitCastFromWhileLoopTest();
1111}1104}
1112fn return_with_implicit_cast_from_while_loop_test() -> %void {1105fn returnWithImplicitCastFromWhileLoopTest() -> %void {
1113 while (true) {1106 while (true) {
1114 return;1107 return;
1115 }1108 }
1116}1109}
11171110
1118#attribute("test")1111#attribute("test")
1119fn return_struct_byval_from_function() {1112fn returnStructByvalFromFunction() {
1120 const bar = make_bar(1234, 5678);1113 const bar = makeBar(1234, 5678);
1121 assert(bar.y == 5678);1114 assert(bar.y == 5678);
1122}1115}
1123struct Bar {1116struct Bar {
1124 x: i32,1117 x: i32,
1125 y: i32,1118 y: i32,
1126}1119}
1127fn make_bar(x: i32, y: i32) -> Bar {1120fn makeBar(x: i32, y: i32) -> Bar {
1128 Bar {1121 Bar {
1129 .x = x,1122 .x = x,
1130 .y = y,1123 .y = y,
...@@ -1132,8 +1125,8 @@ fn make_bar(x: i32, y: i32) -> Bar {...@@ -1132,8 +1125,8 @@ fn make_bar(x: i32, y: i32) -> Bar {
1132}1125}
11331126
1134#attribute("test")1127#attribute("test")
1135fn function_pointers() {1128fn functionPointers() {
1136 const fns = []@typeof(fn1) { fn1, fn2, fn3, fn4, };1129 const fns = []@typeOf(fn1) { fn1, fn2, fn3, fn4, };
1137 for (fns) |f, i| {1130 for (fns) |f, i| {
1138 assert(f() == u32(i) + 5);1131 assert(f() == u32(i) + 5);
1139 }1132 }
...@@ -1146,7 +1139,7 @@ fn fn4() -> u32 {8}...@@ -1146,7 +1139,7 @@ fn fn4() -> u32 {8}
11461139
11471140
1148#attribute("test")1141#attribute("test")
1149fn statically_initalized_struct() {1142fn staticallyInitalizedStruct() {
1150 st_init_str_foo.x += 1;1143 st_init_str_foo.x += 1;
1151 assert(st_init_str_foo.x == 14);1144 assert(st_init_str_foo.x == 14);
1152}1145}
...@@ -1157,7 +1150,7 @@ struct StInitStrFoo {...@@ -1157,7 +1150,7 @@ struct StInitStrFoo {
1157var st_init_str_foo = StInitStrFoo { .x = 13, .y = true, };1150var st_init_str_foo = StInitStrFoo { .x = 13, .y = true, };
11581151
1159#attribute("test")1152#attribute("test")
1160fn statically_initialized_array_literal() {1153fn staticallyInitializedArrayLiteral() {
1161 const y : [4]u8 = st_init_arr_lit_x;1154 const y : [4]u8 = st_init_arr_lit_x;
1162 assert(y[3] == 4);1155 assert(y[3] == 4);
1163}1156}
...@@ -1166,33 +1159,33 @@ const st_init_arr_lit_x = []u8{1,2,3,4};...@@ -1166,33 +1159,33 @@ const st_init_arr_lit_x = []u8{1,2,3,4};
11661159
11671160
1168#attribute("test")1161#attribute("test")
1169fn pointer_to_void_return_type() {1162fn pointerToVoidReturnType() {
1170 %%test_pointer_to_void_return_type();1163 %%testPointerToVoidReturnType();
1171}1164}
1172fn test_pointer_to_void_return_type() -> %void {1165fn testPointerToVoidReturnType() -> %void {
1173 const a = test_pointer_to_void_return_type_2();1166 const a = testPointerToVoidReturnType2();
1174 return *a;1167 return *a;
1175}1168}
1176const test_pointer_to_void_return_type_x = void{};1169const test_pointer_to_void_return_type_x = void{};
1177fn test_pointer_to_void_return_type_2() -> &void {1170fn testPointerToVoidReturnType2() -> &void {
1178 return &test_pointer_to_void_return_type_x;1171 return &test_pointer_to_void_return_type_x;
1179}1172}
11801173
11811174
1182#attribute("test")1175#attribute("test")
1183fn call_result_of_if_else_expression() {1176fn callResultOfIfElseExpression() {
1184 assert(str.eql(f2(true), "a"));1177 assert(str.eql(f2(true), "a"));
1185 assert(str.eql(f2(false), "b"));1178 assert(str.eql(f2(false), "b"));
1186}1179}
1187fn f2(x: bool) -> []u8 {1180fn f2(x: bool) -> []u8 {
1188 return (if (x) f_a else f_b)();1181 return (if (x) fA else fB)();
1189}1182}
1190fn f_a() -> []u8 { "a" }1183fn fA() -> []u8 { "a" }
1191fn f_b() -> []u8 { "b" }1184fn fB() -> []u8 { "b" }
11921185
11931186
1194#attribute("test")1187#attribute("test")
1195fn const_expression_eval_handling_of_variables() {1188fn constExpressionEvalHandlingOfVariables() {
1196 var x = true;1189 var x = true;
1197 while (x) {1190 while (x) {
1198 x = false;1191 x = false;
...@@ -1202,7 +1195,7 @@ fn const_expression_eval_handling_of_variables() {...@@ -1202,7 +1195,7 @@ fn const_expression_eval_handling_of_variables() {
12021195
12031196
1204#attribute("test")1197#attribute("test")
1205fn constant_enum_initialization_with_differing_sizes() {1198fn constantEnumInitializationWithDifferingSizes() {
1206 test3_1(test3_foo);1199 test3_1(test3_foo);
1207 test3_2(test3_bar);1200 test3_2(test3_bar);
1208}1201}
...@@ -1240,22 +1233,22 @@ fn test3_2(f: Test3Foo) {...@@ -1240,22 +1233,22 @@ fn test3_2(f: Test3Foo) {
12401233
12411234
1242#attribute("test")1235#attribute("test")
1243fn pub_enum() {1236fn pubEnum() {
1244 pub_enum_test(other.APubEnum.Two);1237 pubEnumTest(other.APubEnum.Two);
1245}1238}
1246fn pub_enum_test(foo: other.APubEnum) {1239fn pubEnumTest(foo: other.APubEnum) {
1247 assert(foo == other.APubEnum.Two);1240 assert(foo == other.APubEnum.Two);
1248}1241}
12491242
12501243
1251#attribute("test")1244#attribute("test")
1252fn cast_with_imported_symbol() {1245fn castWithImportedSymbol() {
1253 assert(other.size_t(42) == 42);1246 assert(other.size_t(42) == 42);
1254}1247}
12551248
12561249
1257#attribute("test")1250#attribute("test")
1258fn while_with_continue_expr() {1251fn whileWithContinueExpr() {
1259 var sum: i32 = 0;1252 var sum: i32 = 0;
1260 {var i: i32 = 0; while (i < 10; i += 1) {1253 {var i: i32 = 0; while (i < 10; i += 1) {
1261 if (i == 5) continue;1254 if (i == 5) continue;
...@@ -1266,22 +1259,22 @@ fn while_with_continue_expr() {...@@ -1266,22 +1259,22 @@ fn while_with_continue_expr() {
12661259
12671260
1268#attribute("test")1261#attribute("test")
1269fn for_loop_with_pointer_elem_var() {1262fn forLoopWithPointerElemVar() {
1270 const source = "abcdefg";1263 const source = "abcdefg";
1271 var target: [source.len]u8 = undefined;1264 var target: [source.len]u8 = undefined;
1272 @memcpy(&target[0], &source[0], source.len);1265 @memcpy(&target[0], &source[0], source.len);
1273 mangle_string(target);1266 mangleString(target);
1274 assert(str.eql(target, "bcdefgh"));1267 assert(str.eql(target, "bcdefgh"));
1275}1268}
1276#static_eval_enable(false)1269#static_eval_enable(false)
1277fn mangle_string(s: []u8) {1270fn mangleString(s: []u8) {
1278 for (s) |*c| {1271 for (s) |*c| {
1279 *c += 1;1272 *c += 1;
1280 }1273 }
1281}1274}
12821275
1283#attribute("test")1276#attribute("test")
1284fn empty_struct_method_call() {1277fn emptyStructMethodCall() {
1285 const es = EmptyStruct{};1278 const es = EmptyStruct{};
1286 assert(es.method() == 1234);1279 assert(es.method() == 1234);
1287}1280}
...@@ -1296,48 +1289,48 @@ fn @"weird function name"() { }...@@ -1296,48 +1289,48 @@ fn @"weird function name"() { }
12961289
12971290
1298#attribute("test")1291#attribute("test")
1299fn return_empty_struct_from_fn() {1292fn returnEmptyStructFromFn() {
1300 test_return_empty_struct_from_fn();1293 testReturnEmptyStructFromFn();
1301 test_return_empty_struct_from_fn_noeval();1294 testReturnEmptyStructFromFnNoeval();
1302}1295}
1303struct EmptyStruct2 {}1296struct EmptyStruct2 {}
1304fn test_return_empty_struct_from_fn() -> EmptyStruct2 {1297fn testReturnEmptyStructFromFn() -> EmptyStruct2 {
1305 EmptyStruct2 {}1298 EmptyStruct2 {}
1306}1299}
1307#static_eval_enable(false)1300#static_eval_enable(false)
1308fn test_return_empty_struct_from_fn_noeval() -> EmptyStruct2 {1301fn testReturnEmptyStructFromFnNoeval() -> EmptyStruct2 {
1309 EmptyStruct2 {}1302 EmptyStruct2 {}
1310}1303}
13111304
1312#attribute("test")1305#attribute("test")
1313fn pass_slice_of_empty_struct_to_fn() {1306fn passSliceOfEmptyStructToFn() {
1314 assert(test_pass_slice_of_empty_struct_to_fn([]EmptyStruct2{ EmptyStruct2{} }) == 1);1307 assert(testPassSliceOfEmptyStructToFn([]EmptyStruct2{ EmptyStruct2{} }) == 1);
1315}1308}
1316fn test_pass_slice_of_empty_struct_to_fn(slice: []EmptyStruct2) -> usize {1309fn testPassSliceOfEmptyStructToFn(slice: []EmptyStruct2) -> usize {
1317 slice.len1310 slice.len
1318}1311}
13191312
13201313
1321#attribute("test")1314#attribute("test")
1322fn pointer_comparison() {1315fn pointerComparison() {
1323 const a = ([]u8)("a");1316 const a = ([]u8)("a");
1324 const b = &a;1317 const b = &a;
1325 assert(ptr_eql(b, b));1318 assert(ptrEql(b, b));
1326}1319}
1327fn ptr_eql(a: &[]u8, b: &[]u8) -> bool {1320fn ptrEql(a: &[]u8, b: &[]u8) -> bool {
1328 a == b1321 a == b
1329}1322}
13301323
1331#attribute("test")1324#attribute("test")
1332fn character_literals() {1325fn characterLiterals() {
1333 assert('\'' == single_quote);1326 assert('\'' == single_quote);
1334}1327}
1335const single_quote = '\'';1328const single_quote = '\'';
13361329
13371330
1338#attribute("test")1331#attribute("test")
1339fn switch_with_multiple_expressions() {1332fn switchWithMultipleExpressions() {
1340 const x: i32 = switch (returns_five()) {1333 const x: i32 = switch (returnsFive()) {
1341 1, 2, 3 => 1,1334 1, 2, 3 => 1,
1342 4, 5, 6 => 2,1335 4, 5, 6 => 2,
1343 else => 3,1336 else => 3,
...@@ -1345,12 +1338,12 @@ fn switch_with_multiple_expressions() {...@@ -1345,12 +1338,12 @@ fn switch_with_multiple_expressions() {
1345 assert(x == 2);1338 assert(x == 2);
1346}1339}
1347#static_eval_enable(false)1340#static_eval_enable(false)
1348fn returns_five() -> i32 { 5 }1341fn returnsFive() -> i32 { 5 }
13491342
13501343
1351#attribute("test")1344#attribute("test")
1352fn switch_on_error_union() {1345fn switchOnErrorUnion() {
1353 const x = switch (returns_ten()) {1346 const x = switch (returnsTen()) {
1354 Ok => |val| val + 1,1347 Ok => |val| val + 1,
1355 ItBroke, NoMem => 1,1348 ItBroke, NoMem => 1,
1356 CrappedOut => 2,1349 CrappedOut => 2,
...@@ -1361,40 +1354,40 @@ error ItBroke;...@@ -1361,40 +1354,40 @@ error ItBroke;
1361error NoMem;1354error NoMem;
1362error CrappedOut;1355error CrappedOut;
1363#static_eval_enable(false)1356#static_eval_enable(false)
1364fn returns_ten() -> %i32 { 10 }1357fn returnsTen() -> %i32 { 10 }
13651358
13661359
1367#attribute("test")1360#attribute("test")
1368fn bool_cmp() {1361fn boolCmp() {
1369 assert(test_bool_cmp(true, false) == false);1362 assert(testBoolCmp(true, false) == false);
1370}1363}
1371#static_eval_enable(false)1364#static_eval_enable(false)
1372fn test_bool_cmp(a: bool, b: bool) -> bool { a == b }1365fn testBoolCmp(a: bool, b: bool) -> bool { a == b }
13731366
13741367
1375#attribute("test")1368#attribute("test")
1376fn take_address_of_parameter() {1369fn takeAddressOfParameter() {
1377 test_take_address_of_parameter(12.34);1370 testTakeAddressOfParameter(12.34);
1378 test_take_address_of_parameter_noeval(12.34);1371 testTakeAddressOfParameterNoeval(12.34);
1379}1372}
1380fn test_take_address_of_parameter(f: f32) {1373fn testTakeAddressOfParameter(f: f32) {
1381 const f_ptr = &f;1374 const f_ptr = &f;
1382 assert(*f_ptr == 12.34);1375 assert(*f_ptr == 12.34);
1383}1376}
1384#static_eval_enable(false)1377#static_eval_enable(false)
1385fn test_take_address_of_parameter_noeval(f: f32) {1378fn testTakeAddressOfParameterNoeval(f: f32) {
1386 const f_ptr = &f;1379 const f_ptr = &f;
1387 assert(*f_ptr == 12.34);1380 assert(*f_ptr == 12.34);
1388}1381}
13891382
13901383
1391#attribute("test")1384#attribute("test")
1392fn array_mult_operator() {1385fn arrayMultOperator() {
1393 assert(str.eql("ab" ** 5, "ababababab"));1386 assert(str.eql("ab" ** 5, "ababababab"));
1394}1387}
13951388
1396#attribute("test")1389#attribute("test")
1397fn string_escapes() {1390fn stringEscapes() {
1398 assert(str.eql("\"", "\x22"));1391 assert(str.eql("\"", "\x22"));
1399 assert(str.eql("\'", "\x27"));1392 assert(str.eql("\'", "\x27"));
1400 assert(str.eql("\n", "\x0a"));1393 assert(str.eql("\n", "\x0a"));
...@@ -1405,11 +1398,11 @@ fn string_escapes() {...@@ -1405,11 +1398,11 @@ fn string_escapes() {
1405}1398}
14061399
1407#attribute("test")1400#attribute("test")
1408fn if_var_maybe_pointer() {1401fn ifVarMaybePointer() {
1409 assert(should_be_a_plus_1(Particle {.a = 14, .b = 1, .c = 1, .d = 1}) == 15);1402 assert(shouldBeAPlus1(Particle {.a = 14, .b = 1, .c = 1, .d = 1}) == 15);
1410}1403}
1411#static_eval_enable(false)1404#static_eval_enable(false)
1412fn should_be_a_plus_1(p: Particle) -> u64 {1405fn shouldBeAPlus1(p: Particle) -> u64 {
1413 var maybe_particle: ?Particle = p;1406 var maybe_particle: ?Particle = p;
1414 if (const *particle ?= maybe_particle) {1407 if (const *particle ?= maybe_particle) {
1415 particle.a += 1;1408 particle.a += 1;
...@@ -1427,7 +1420,7 @@ struct Particle {...@@ -1427,7 +1420,7 @@ struct Particle {
1427}1420}
14281421
1429#attribute("test")1422#attribute("test")
1430fn assign_to_if_var_ptr() {1423fn assignToIfVarPtr() {
1431 var maybe_bool: ?bool = true;1424 var maybe_bool: ?bool = true;
14321425
1433 if (const *b ?= maybe_bool) {1426 if (const *b ?= maybe_bool) {
...@@ -1452,85 +1445,85 @@ fn fence() {...@@ -1452,85 +1445,85 @@ fn fence() {
1452}1445}
14531446
1454#attribute("test")1447#attribute("test")
1455fn unsigned_wrapping() {1448fn unsignedWrapping() {
1456 test_unsigned_wrapping_eval(@max_value(u32));1449 testUnsignedWrappingEval(@maxValue(u32));
1457 test_unsigned_wrapping_noeval(@max_value(u32));1450 testUnsignedWrappingNoeval(@maxValue(u32));
1458}1451}
1459fn test_unsigned_wrapping_eval(x: u32) {1452fn testUnsignedWrappingEval(x: u32) {
1460 const zero = x +% 1;1453 const zero = x +% 1;
1461 assert(zero == 0);1454 assert(zero == 0);
1462 const orig = zero -% 1;1455 const orig = zero -% 1;
1463 assert(orig == @max_value(u32));1456 assert(orig == @maxValue(u32));
1464}1457}
1465#static_eval_enable(false)1458#static_eval_enable(false)
1466fn test_unsigned_wrapping_noeval(x: u32) {1459fn testUnsignedWrappingNoeval(x: u32) {
1467 const zero = x +% 1;1460 const zero = x +% 1;
1468 assert(zero == 0);1461 assert(zero == 0);
1469 const orig = zero -% 1;1462 const orig = zero -% 1;
1470 assert(orig == @max_value(u32));1463 assert(orig == @maxValue(u32));
1471}1464}
14721465
1473#attribute("test")1466#attribute("test")
1474fn signed_wrapping() {1467fn signedWrapping() {
1475 test_signed_wrapping_eval(@max_value(i32));1468 testSignedWrappingEval(@maxValue(i32));
1476 test_signed_wrapping_noeval(@max_value(i32));1469 testSignedWrappingNoeval(@maxValue(i32));
1477}1470}
1478fn test_signed_wrapping_eval(x: i32) {1471fn testSignedWrappingEval(x: i32) {
1479 const min_val = x +% 1;1472 const min_val = x +% 1;
1480 assert(min_val == @min_value(i32));1473 assert(min_val == @minValue(i32));
1481 const max_val = min_val -% 1;1474 const max_val = min_val -% 1;
1482 assert(max_val == @max_value(i32));1475 assert(max_val == @maxValue(i32));
1483}1476}
1484#static_eval_enable(false)1477#static_eval_enable(false)
1485fn test_signed_wrapping_noeval(x: i32) {1478fn testSignedWrappingNoeval(x: i32) {
1486 const min_val = x +% 1;1479 const min_val = x +% 1;
1487 assert(min_val == @min_value(i32));1480 assert(min_val == @minValue(i32));
1488 const max_val = min_val -% 1;1481 const max_val = min_val -% 1;
1489 assert(max_val == @max_value(i32));1482 assert(max_val == @maxValue(i32));
1490}1483}
14911484
1492#attribute("test")1485#attribute("test")
1493fn negation_wrapping() {1486fn negationWrapping() {
1494 test_negation_wrapping_eval(@min_value(i16));1487 testNegationWrappingEval(@minValue(i16));
1495 test_negation_wrapping_noeval(@min_value(i16));1488 testNegationWrappingNoeval(@minValue(i16));
1496}1489}
1497fn test_negation_wrapping_eval(x: i16) {1490fn testNegationWrappingEval(x: i16) {
1498 assert(x == -32768);1491 assert(x == -32768);
1499 const neg = -%x;1492 const neg = -%x;
1500 assert(neg == -32768);1493 assert(neg == -32768);
1501}1494}
1502#static_eval_enable(false)1495#static_eval_enable(false)
1503fn test_negation_wrapping_noeval(x: i16) {1496fn testNegationWrappingNoeval(x: i16) {
1504 assert(x == -32768);1497 assert(x == -32768);
1505 const neg = -%x;1498 const neg = -%x;
1506 assert(neg == -32768);1499 assert(neg == -32768);
1507}1500}
15081501
1509#attribute("test")1502#attribute("test")
1510fn shl_wrapping() {1503fn shlWrapping() {
1511 test_shl_wrapping_eval(@max_value(u16));1504 testShlWrappingEval(@maxValue(u16));
1512 test_shl_wrapping_noeval(@max_value(u16));1505 testShlWrappingNoeval(@maxValue(u16));
1513}1506}
1514fn test_shl_wrapping_eval(x: u16) {1507fn testShlWrappingEval(x: u16) {
1515 const shifted = x <<% 1;1508 const shifted = x <<% 1;
1516 assert(shifted == 65534);1509 assert(shifted == 65534);
1517}1510}
1518#static_eval_enable(false)1511#static_eval_enable(false)
1519fn test_shl_wrapping_noeval(x: u16) {1512fn testShlWrappingNoeval(x: u16) {
1520 const shifted = x <<% 1;1513 const shifted = x <<% 1;
1521 assert(shifted == 65534);1514 assert(shifted == 65534);
1522}1515}
15231516
1524#attribute("test")1517#attribute("test")
1525fn shl_with_overflow() {1518fn shlWithOverflow() {
1526 var result: u16 = undefined;1519 var result: u16 = undefined;
1527 assert(@shl_with_overflow(u16, 0b0010111111111111, 3, &result));1520 assert(@shlWithOverflow(u16, 0b0010111111111111, 3, &result));
1528 assert(!@shl_with_overflow(u16, 0b0010111111111111, 2, &result));1521 assert(!@shlWithOverflow(u16, 0b0010111111111111, 2, &result));
1529 assert(result == 0b1011111111111100);1522 assert(result == 0b1011111111111100);
1530}1523}
15311524
1532#attribute("test")1525#attribute("test")
1533fn c_string_concatenation() {1526fn cStringConcatenation() {
1534 const a = c"OK" ++ c" IT " ++ c"WORKED";1527 const a = c"OK" ++ c" IT " ++ c"WORKED";
1535 const b = c"OK IT WORKED";1528 const b = c"OK IT WORKED";
15361529
...@@ -1544,22 +1537,22 @@ fn c_string_concatenation() {...@@ -1544,22 +1537,22 @@ fn c_string_concatenation() {
1544}1537}
15451538
1546#attribute("test")1539#attribute("test")
1547fn generic_struct() {1540fn genericStruct() {
1548 var a1 = GenNode(i32) {.value = 13, .next = null,};1541 var a1 = GenNode(i32) {.value = 13, .next = null,};
1549 var b1 = GenNode(bool) {.value = true, .next = null,};1542 var b1 = GenNode(bool) {.value = true, .next = null,};
1550 assert(a1.value == 13);1543 assert(a1.value == 13);
1551 assert(a1.value == a1.get_val());1544 assert(a1.value == a1.getVal());
1552 assert(b1.get_val());1545 assert(b1.getVal());
1553}1546}
1554struct GenNode(T: type) {1547struct GenNode(T: type) {
1555 value: T,1548 value: T,
1556 next: ?&GenNode(T),1549 next: ?&GenNode(T),
1557 fn get_val(n: &const GenNode(T)) -> T { n.value }1550 fn getVal(n: &const GenNode(T)) -> T { n.value }
1558}1551}
15591552
1560#attribute("test")1553#attribute("test")
1561fn cast_slice_to_u8_slice() {1554fn castSliceToU8Slice() {
1562 assert(@sizeof(i32) == 4);1555 assert(@sizeOf(i32) == 4);
1563 var big_thing_array = []i32{1, 2, 3, 4};1556 var big_thing_array = []i32{1, 2, 3, 4};
1564 const big_thing_slice: []i32 = big_thing_array;1557 const big_thing_slice: []i32 = big_thing_array;
1565 const bytes = ([]u8)(big_thing_slice);1558 const bytes = ([]u8)(big_thing_slice);
...@@ -1572,14 +1565,14 @@ fn cast_slice_to_u8_slice() {...@@ -1572,14 +1565,14 @@ fn cast_slice_to_u8_slice() {
1572 const big_thing_again = ([]i32)(bytes);1565 const big_thing_again = ([]i32)(bytes);
1573 assert(big_thing_again[2] == 3);1566 assert(big_thing_again[2] == 3);
1574 big_thing_again[2] = -1;1567 big_thing_again[2] = -1;
1575 assert(bytes[8] == @max_value(u8));1568 assert(bytes[8] == @maxValue(u8));
1576 assert(bytes[9] == @max_value(u8));1569 assert(bytes[9] == @maxValue(u8));
1577 assert(bytes[10] == @max_value(u8));1570 assert(bytes[10] == @maxValue(u8));
1578 assert(bytes[11] == @max_value(u8));1571 assert(bytes[11] == @maxValue(u8));
1579}1572}
15801573
1581#attribute("test")1574#attribute("test")
1582fn float_division() {1575fn floatDivision() {
1583 assert(fdiv32(12.0, 3.0) == 4.0);1576 assert(fdiv32(12.0, 3.0) == 4.0);
1584}1577}
1585#static_eval_enable(false)1578#static_eval_enable(false)
...@@ -1588,16 +1581,16 @@ fn fdiv32(a: f32, b: f32) -> f32 {...@@ -1588,16 +1581,16 @@ fn fdiv32(a: f32, b: f32) -> f32 {
1588}1581}
15891582
1590#attribute("test")1583#attribute("test")
1591fn exact_division() {1584fn exactDivision() {
1592 assert(div_exact(55, 11) == 5);1585 assert(divExact(55, 11) == 5);
1593}1586}
1594#static_eval_enable(false)1587#static_eval_enable(false)
1595fn div_exact(a: u32, b: u32) -> u32 {1588fn divExact(a: u32, b: u32) -> u32 {
1596 @div_exact(a, b)1589 @divExact(a, b)
1597}1590}
15981591
1599#attribute("test")1592#attribute("test")
1600fn null_literal_outside_function() {1593fn nullLiteralOutsideFunction() {
1601 const is_null = if (const _ ?= here_is_a_null_literal.context) false else true;1594 const is_null = if (const _ ?= here_is_a_null_literal.context) false else true;
1602 assert(is_null);1595 assert(is_null);
1603}1596}
...@@ -1610,15 +1603,15 @@ const here_is_a_null_literal = SillyStruct {...@@ -1610,15 +1603,15 @@ const here_is_a_null_literal = SillyStruct {
16101603
1611#attribute("test")1604#attribute("test")
1612fn truncate() {1605fn truncate() {
1613 assert(test_truncate(0x10fd) == 0xfd);1606 assert(testTruncate(0x10fd) == 0xfd);
1614}1607}
1615#static_eval_enable(false)1608#static_eval_enable(false)
1616fn test_truncate(x: u32) -> u8 {1609fn testTruncate(x: u32) -> u8 {
1617 @truncate(u8, x)1610 @truncate(u8, x)
1618}1611}
16191612
1620#attribute("test")1613#attribute("test")
1621fn const_decls_in_struct() {1614fn constDeclsInStruct() {
1622 assert(GenericDataThing(3).count_plus_one == 4);1615 assert(GenericDataThing(3).count_plus_one == 4);
1623}1616}
1624struct GenericDataThing(count: isize) {1617struct GenericDataThing(count: isize) {
...@@ -1626,30 +1619,30 @@ struct GenericDataThing(count: isize) {...@@ -1626,30 +1619,30 @@ struct GenericDataThing(count: isize) {
1626}1619}
16271620
1628#attribute("test")1621#attribute("test")
1629fn use_generic_param_in_generic_param() {1622fn useGenericParamInGenericParam() {
1630 assert(a_generic_fn(i32, 3, 4) == 7);1623 assert(aGenericFn(i32, 3, 4) == 7);
1631}1624}
1632fn a_generic_fn(inline T: type, inline a: T, b: T) -> T {1625fn aGenericFn(inline T: type, inline a: T, b: T) -> T {
1633 return a + b;1626 return a + b;
1634}1627}
16351628
16361629
1637#attribute("test")1630#attribute("test")
1638fn namespace_depends_on_compile_var() {1631fn namespaceDependsOnCompileVar() {
1639 if (some_namespace.a_bool) {1632 if (some_namespace.a_bool) {
1640 assert(some_namespace.a_bool);1633 assert(some_namespace.a_bool);
1641 } else {1634 } else {
1642 assert(!some_namespace.a_bool);1635 assert(!some_namespace.a_bool);
1643 }1636 }
1644}1637}
1645const some_namespace = switch(@compile_var("os")) {1638const some_namespace = switch(@compileVar("os")) {
1646 linux => @import("a.zig"),1639 linux => @import("a.zig"),
1647 else => @import("b.zig"),1640 else => @import("b.zig"),
1648};1641};
16491642
16501643
1651#attribute("test")1644#attribute("test")
1652fn unsigned_64_bit_division() {1645fn unsigned64BitDivision() {
1653 const result = div(1152921504606846976, 34359738365);1646 const result = div(1152921504606846976, 34359738365);
1654 assert(result.quotient == 33554432);1647 assert(result.quotient == 33554432);
1655 assert(result.remainder == 100663296);1648 assert(result.remainder == 100663296);
...@@ -1667,16 +1660,16 @@ struct DivResult {...@@ -1667,16 +1660,16 @@ struct DivResult {
1667}1660}
16681661
1669#attribute("test")1662#attribute("test")
1670fn int_type_builtin() {1663fn intTypeBuiltin() {
1671 assert(@int_type(true, 8) == i8);1664 assert(@intType(true, 8) == i8);
1672 assert(@int_type(true, 16) == i16);1665 assert(@intType(true, 16) == i16);
1673 assert(@int_type(true, 32) == i32);1666 assert(@intType(true, 32) == i32);
1674 assert(@int_type(true, 64) == i64);1667 assert(@intType(true, 64) == i64);
16751668
1676 assert(@int_type(false, 8) == u8);1669 assert(@intType(false, 8) == u8);
1677 assert(@int_type(false, 16) == u16);1670 assert(@intType(false, 16) == u16);
1678 assert(@int_type(false, 32) == u32);1671 assert(@intType(false, 32) == u32);
1679 assert(@int_type(false, 64) == u64);1672 assert(@intType(false, 64) == u64);
16801673
1681 assert(i8.bit_count == 8);1674 assert(i8.bit_count == 8);
1682 assert(i16.bit_count == 16);1675 assert(i16.bit_count == 16);
...@@ -1698,15 +1691,15 @@ fn int_type_builtin() {...@@ -1698,15 +1691,15 @@ fn int_type_builtin() {
1698}1691}
16991692
1700#attribute("test")1693#attribute("test")
1701fn int_to_enum() {1694fn intToEnum() {
1702 test_int_to_enum_eval(3);1695 testIntToEnumEval(3);
1703 test_int_to_enum_noeval(3);1696 testIntToEnumNoeval(3);
1704}1697}
1705fn test_int_to_enum_eval(x: i32) {1698fn testIntToEnumEval(x: i32) {
1706 assert(IntToEnumNumber(x) == IntToEnumNumber.Three);1699 assert(IntToEnumNumber(x) == IntToEnumNumber.Three);
1707}1700}
1708#static_eval_enable(false)1701#static_eval_enable(false)
1709fn test_int_to_enum_noeval(x: i32) {1702fn testIntToEnumNoeval(x: i32) {
1710 assert(IntToEnumNumber(x) == IntToEnumNumber.Three);1703 assert(IntToEnumNumber(x) == IntToEnumNumber.Three);
1711}1704}
1712enum IntToEnumNumber {1705enum IntToEnumNumber {