harec

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

16-defer.ha (874B)


      1 use rt;
      2 
      3 let x: int = 10;
      4 
      5 fn basics() void = {
      6 	assert(x == 10);
      7 	defer x = 20;
      8 	assert(x == 10);
      9 	if (true) {
     10 		return;
     11 	};
     12 	defer x = 30;
     13 };
     14 
     15 fn scope() void = {
     16 	let x = 10;
     17 	{
     18 		defer x = 20;
     19 		assert(x == 10);
     20 	};
     21 	assert(x == 20);
     22 };
     23 
     24 fn loops() void = {
     25 	let x = 0;
     26 	for (let i = 0; i < 5; i += 1) {
     27 		defer x += 1;
     28 		assert(x == i);
     29 	};
     30 	assert(x == 5);
     31 };
     32 
     33 fn control() void = {
     34 	let x = 0;
     35 	for (let i = 0; i < 5; i += 1) {
     36 		if (true) {
     37 			continue;
     38 		};
     39 		defer x += 1;
     40 	};
     41 	assert(x == 0);
     42 
     43 	for (let i = 0; i < 5; i += 1) {
     44 		defer x += 1;
     45 		if (true) {
     46 			break;
     47 		};
     48 		abort();
     49 	};
     50 	assert(x == 1);
     51 };
     52 
     53 fn noreturn() void = {
     54 	defer x = 30;
     55 	for (true) {
     56 		defer x = 20;
     57 		exit();
     58 	};
     59 };
     60 
     61 @noreturn fn exit() void = {
     62 	assert(x == 30);
     63 	rt::exit(0);
     64 };
     65 
     66 export fn main() void = {
     67 	basics();
     68 	assert(x == 20);
     69 	scope();
     70 	loops();
     71 	control();
     72 	noreturn();
     73 };