aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: 7825d08101acefecda86573d21e78b46f9dd591a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>

#include "file.h"
#include "args.h"
#include "diag.h"
#include "sema.h"
#include "lexer.h"
#include "parser.h"
#include "codegen.h"

int main(int argc, char** argv)
{
	struct Args args;

	enum ParseResult result = parse_args(argc, argv, &args);
	if (result == PARSE_EXIT)
		return 0;
	if (result == PARSE_ERROR)
		return 1;

	if (args.target == TARGET_MASM)
	{
		report_error_message("the masm target is not implemented yet");
		return 1;
	}

	struct File source;
	if (!read_file(args.input_path, &source))
		return 1;

	struct Lexer lexer = create_lexer(source.data);
	lexer.name = args.input_path;

	struct Program program;
	if (!parse_program(&lexer, &program))
	{
		free_program(&program);
		free_file(&source);
		return 1;
	}

	struct Source diagnostics = { args.input_path, source.data };
	if (!analyze_program(diagnostics, &program))
	{
		free_program(&program);
		free_file(&source);
		return 1;
	}

	FILE* out = stdout;
	if (args.output_path != NULL)
	{
		out = fopen(args.output_path, "w");
		if (out == NULL)
		{
			char message[256];
			snprintf(message, sizeof(message), "could not open '%s' for writing", args.output_path);
			report_error_message(message);
			free_program(&program);
			free_file(&source);
			return 1;
		}
	}

	if (args.target == TARGET_FASM)
		generate_fasm(&program, out);
	else if (args.target == TARGET_ARM64)
		generate_aarch64(&program, out);
	else
		generate_nasm(&program, out);

	if (out != stdout)
		fclose(out);

	free_program(&program);
	free_file(&source);
}