harec

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

compile.ha (980B)


      1 // Runs the Hare compiler and returns the exit status.
      2 export fn compile(src: const str) int = {
      3 	let status = 0;
      4 	let pipefd = [-1, -1];
      5 	assert(pipe2(&pipefd, 0) == 0);
      6 
      7 	const child = fork();
      8 	if (child == 0) {
      9 		close(pipefd[1]);
     10 		dup2(pipefd[0], 0);
     11 		close(1);
     12 		close(2);
     13 
     14 		const path = "./harec\0";
     15 		const argv: [_]nullable *const char = [
     16 			constchar(path),
     17 			constchar("-\0"),
     18 			null
     19 		];
     20 		const envp: [_]nullable *const char = [
     21 			constchar("HARECACHE=mod\0"),
     22 			null
     23 		];
     24 		execve(constchar(path), &argv, &envp);
     25 		abort();
     26 	} else {
     27 		assert(child != -1, "fork(2) failed");
     28 		close(pipefd[0]);
     29 
     30 		const buf = constchar(src): *const [*]u8;
     31 		for (let n = 0z; n < len(src)) {
     32 			let m = write(pipefd[1], &buf[n], len(src) - n);
     33 			assert(m > 0, "write(2) failed");
     34 			n += m;
     35 		};
     36 
     37 		close(pipefd[1]);
     38 		wait4(child, &status, 0, null);
     39 	};
     40 
     41 	return if (wifexited(status)) wexitstatus(status)
     42 		else if (wifsignaled(status)) wtermsig(status)
     43 		else abort();
     44 };