harec

[hare] Hare compiler, written in C11 for POSIX OSs
Log | Files | Refs | README | LICENSE

19-append.ha (2020B)


      1 use rt;
      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(rt::compile("
     72 		let x: []u8 = [0u8];
     73 		let y: int = 42;
     74 		append(x, y);
     75 	") != 0); // object member type != value type
     76 	assert(rt::compile("
     77 		let x: []u8 = [0u8];
     78 		let y = 42u8;
     79 		append(x, y...);
     80 	") != 0); // value is not an array or a slice
     81 	assert(rt::compile("
     82 		let x: []u8 = [0u8];
     83 		let y: []int = [42];
     84 		append(x, y...);
     85 	") != 0); // object member type != value member type
     86 	assert(rt::compile("
     87 		let x: []u8 = [0u8];
     88 		append(x, [42i...], 5);
     89 	") != 0); // same as above, but for an expression with length
     90 	assert(rt::compile("
     91 		let x: []u8 = [0u8];
     92 		append(x, [0u8...], 2i);
     93 	") != 0); // length expression is not assignable to size
     94 	assert(rt::compile("
     95 		let x: []u8 = [0u8];
     96 		append(x, [42], 3);
     97 	") != 0); // must be an expandable array
     98 };
     99 
    100 export fn main() void = {
    101 	basics();
    102 	multi();
    103 	_static();
    104 	withlength();
    105 	typehints();
    106 	reject();
    107 };