harec

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

03-pointers.ha (1779B)


      1 use rt;
      2 
      3 type intp = *int;
      4 
      5 fn basics() void = {
      6 	let x = 42;
      7 	let y: intp = &x;
      8 	assert(*y == 42);
      9 	*y = 1337;
     10 	assert(x == 1337);
     11 };
     12 
     13 fn _nullable() void = {
     14 	let x: nullable *int = null;
     15 	assert(x == null);
     16 	let y = 42;
     17 	x = &y;
     18 	assert(*(x: *int) == 42);
     19 
     20 	assert(rt::compile(
     21 		"fn test() void = { let x: nullable *int = null; let z = *x; };",
     22 	) != 0);
     23 };
     24 
     25 fn casts() void = {
     26 	let a: *uint = &4u;
     27 	let b = a: *void;
     28 	let c = b: *uint;
     29 	assert(a == c && *c == 4);
     30 
     31 	let a: nullable *uint = &7u;
     32 	let b = a: *uint;
     33 	assert(b == a && *b == 7);
     34 
     35 	let a: nullable *uint = &10u;
     36 	let b = a as *uint;
     37 	assert(b == a && *b == 10);
     38 
     39 	let a: nullable *int = &4;
     40 	assert(a is *int);
     41 
     42 	let a: nullable *int = null;
     43 	assert(a is null);
     44 	assert((a as null): nullable *void == null);
     45 
     46 	let a: nullable *int = &4;
     47 	a as nullable *int;
     48 };
     49 
     50 fn reject() void = {
     51 	assert(rt::compile("
     52 		type s = null;
     53 		fn test() void = {
     54 			void;
     55 		};
     56 	") != 0);
     57 	assert(rt::compile("
     58 		fn test() void = {
     59 			let a = &3: null;
     60 		};
     61 	") != 0);
     62 	assert(rt::compile("
     63 		fn test() void = {
     64 			let b: nullable *int = null;
     65 			let a = b as null;
     66 		};
     67 	") != 0);
     68 	assert(rt::compile("
     69 		fn test() void = {
     70 			let a = (null, 3);
     71 		};
     72 	") != 0);
     73 	assert(rt::compile("
     74 		fn test() void = {
     75 			let a: []null = [null];
     76 		};
     77 	") != 0);
     78 	assert(rt::compile("
     79 		fn test() void = {
     80 			let a = [null];
     81 		};
     82 	") != 0);
     83 	assert(rt::compile("
     84 		fn test() void = {
     85 			let a: [_]null = [null];
     86 		};
     87 	") != 0);
     88 	assert(rt::compile("
     89 		fn test() void = {
     90 			let a = null;
     91 		};
     92 	") != 0);
     93 
     94 	// type assertions on non-nullable pointers are prohibited
     95 	assert(rt::compile("
     96 		fn test() void = {
     97 			let a: *int = &4;
     98 			assert(a as *int);
     99 		};
    100 	") != 0);
    101 };
    102 
    103 export fn main() void = {
    104 	basics();
    105 	_nullable();
    106 	casts();
    107 	reject();
    108 };