ox

The Ox programming language, compiler and tools (WIP)
Log | Files | Refs | README | LICENSE

main.c (2103B)



#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "file.h"
#include "utils.h"
#include "lexer.h"
#include "parser.h"
#include "sem.h"
#include "gen.h"

int
main(int argc, char* argv[])
{
	if (argc < 2) {
		printf("Usage: %s <file>\n", argv[0]);
		return 1;
	}

	const char* contents = NULL;
	const char* filename = NULL;
	const char* flag = NULL;

	filename = argv[1];
	switch (argc) {
	case 2:
		filename = argv[1];
		break;
	case 3:
		// --quiet, --exec
		flag = argv[1];
		filename = argv[2];
		break;

	default:
		panic("unsupported arguments");
	}

	contents = readfile(filename);

	bool quiet_flag = flag == NULL ? false : (strcmp(flag, "--quiet") == 0);
	bool exec_flag = flag == NULL ? false : (strcmp(flag, "--exec") == 0);

	if (contents == NULL) { panic("error reading file: %s", filename); }

	printf("--- lex --- \n");

	Lexer lex;
	lexer_lex(&lex, filename, contents);
	// lexer_print(&lex);

	Parser par = parser_init(&lex);

	printf("--- par --- \n");

	Ast ast;
	parser_parse(&ast, &par);
	ast_print(&ast);

	printf("--- sem --- \n");

	Scope program_scope = scope_init(ast.node);
	scope_program(&program_scope, &ast);
	scope_print(&program_scope, &ast);

	printf("--- gen --- \n");

	Gen gen = gen_init(&program_scope, contents, ast.node, quiet_flag);
	gen_next(&gen, ast.node);

	gcc_jit_result* result;

	/* Compile the code.  */
	result = gcc_jit_context_compile(gen.ctx);
	if (!result) { panic("compilation failed"); }

	/* Extract the generated code from "result".  */
	if (exec_flag) {
		printf("--- exec start --- \n");

		typedef int (*fn_type)(void);
		fn_type starting_func = (fn_type)gcc_jit_result_get_code(result, "main");

		if (!starting_func) {
			fprintf(stderr, "NULL gcc_jit_result_get_code\n");
			exit(1);
		}
		starting_func();

		printf("--- exec end --- \n");
	}

	fflush(stdout);

	gcc_jit_context_set_bool_option(gen.ctx, GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 0);
	gcc_jit_context_compile_to_file(gen.ctx, GCC_JIT_OUTPUT_KIND_EXECUTABLE, "out");

	gcc_jit_context_release(gen.ctx);
	gcc_jit_result_release(result);
}