git.haldean.org cvm / 6fd33e3
Support '#include' preprocessor directive. Note that because of how functions are called at the moment, including headers doesn't do a ton of good unless they contain the function definitions, not just stubs. Also, you can't pass more than one source file to the compiler at the moment, so you can't use other C code. Given that, I am adding "cvmlib", a dinky implementation of the bits of libc that I use. For now, that's just putc, because I'm tired of editing the assembly to add PRINT instructions. Will Brown 9 years ago
5 changed file(s) with 41 addition(s) and 10 deletion(s). Raw diff Collapse all Expand all
22 from translate import translate
33 from link import link
44 from binary import write_binary, parse_instructions
5 from preprocess import preprocess
56
67 def run(args):
78 if args.input_file:
2728
2829 with open(args.output, 'w') as binout:
2930 write_binary(instructions, binout)
30
31 def preprocess(source):
32 result = ''
33 for line in source.split('\n'):
34 if not line.startswith('#'):
35 result += line + '\n'
36 else:
37 result += '\n'
38 return result
00 def link(glob, funcs, init_code):
1 code = []
1 code = [('ldconst', funcs['main'].frame_size), ('call', ('main', 'func'))]
22 code.extend(init_code)
33 func_locations = {}
44
0 import os
1
2 include_paths = ['.', './cvmlib']
3
4 def expand_directive(line, defs):
5 command, args = line.split(' ', 1)
6 if command == '#include':
7 path = args.strip('<>" ')
8 for searchdir in include_paths:
9 try:
10 with open(searchdir + '/' + path) as f:
11 return f.read()
12 except IOError:
13 pass
14 raise Exception(
15 'Could not find included file %s in paths %s.' % (path, include_paths))
16
17 def preprocess(source):
18 result = ''
19 for line in source.split('\n'):
20 if not line.startswith('#'):
21 result += line + '\n'
22 else:
23 result += expand_directive(line, {})
24 return result
0 void putc(char c) {
1 c;
2 asm("PRINT");
3 return;
4 }
0 #include <cvmstdio.c>
1
2 int main() {
3 char x;
4 for (x = 'a'; x <= 'z'; x++) {
5 putc(x);
6 }
7 putc('\n');
8 }