19-append.ha (2317B)
1 use rt::{compile, exited, EXIT_SUCCESS}; 2 3 fn basics() void = { 4 let x: []int = []; 5 append(x, 1); 6 append(x, 2); 7 append(x, 3); 8 assert(len(x) == 3); 9 assert(x[0] == 1 && x[1] == 2 && x[2] == 3); 10 free(x); 11 }; 12 13 fn multi() void = { 14 let x: []int = []; 15 append(x, [1, 2, 3]...); 16 assert(len(x) == 3); 17 18 let y: []int = [4, 5, 6]; 19 append(x, y...); 20 assert(len(x) == 6); 21 22 for (let i = 0z; i < len(x); i += 1) { 23 assert(x[i] == i: int + 1); 24 }; 25 26 free(x); 27 }; 28 29 fn _static() void = { 30 let buf: [32]int = [0...]; 31 let x = buf[..0]; 32 static append(x, 1); 33 static append(x, 2); 34 static append(x, 3); 35 assert(len(x) == 3); 36 37 static append(x, [4, 5, 6]...); 38 assert(len(x) == 6); 39 40 for (let i = 0z; i < len(x); i += 1) { 41 assert(x[i] == i: int + 1); 42 assert(buf[i] == i: int + 1); 43 }; 44 }; 45 46 fn withlength() void = { 47 let x: []int = []; 48 append(x, [42...], 10); 49 50 assert(len(x) == 10); 51 for (let i = 0z; i < len(x); i += 1) { 52 assert(x[i] == 42); 53 }; 54 55 free(x); 56 }; 57 58 fn typehints() void = { 59 let x: []u8 = []; 60 append(x, 42); 61 append(x, [42]...); 62 append(x, [42...], 3); 63 assert(len(x) == 5); 64 for (let i = 0z; i < 5; i += 1) { 65 assert(x[i] == 42u8); 66 }; 67 free(x); 68 }; 69 70 fn reject() void = { 71 assert(compile(" 72 let x: []u8 = [0u8]; 73 let y: int = 42; 74 append(x, y); 75 ") as exited != EXIT_SUCCESS); // object member type != value type 76 assert(compile(" 77 let x: []u8 = [0u8]; 78 let y = 42u8; 79 append(x, y...); 80 ") as exited != EXIT_SUCCESS); // value is not an array or a slice 81 assert(compile(" 82 let x: []u8 = [0u8]; 83 let y: []int = [42]; 84 append(x, y...); 85 ") as exited != EXIT_SUCCESS); // object member type != value member type 86 assert(compile(" 87 let x: []u8 = [0u8]; 88 append(x, [42i...], 5); 89 ") as exited != EXIT_SUCCESS); // same as above, but for an expression with length 90 assert(compile(" 91 let x: []u8 = [0u8]; 92 append(x, [0u8...], 2i); 93 ") as exited != EXIT_SUCCESS); // length expression is not assignable to size 94 assert(compile(" 95 let x: []u8 = [0u8]; 96 append(x, [42], 3); 97 ") as exited != EXIT_SUCCESS); // must be an expandable array 98 assert(compile(" 99 let x: []u8 = [0u8]; 100 let x: nullable *[]u8 = &x; 101 append(x, 42); 102 ") as exited != EXIT_SUCCESS); // object member type is nullable pointer 103 }; 104 105 export fn main() void = { 106 basics(); 107 multi(); 108 _static(); 109 withlength(); 110 typehints(); 111 reject(); 112 };