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
10 years ago
2 | 2 |
from translate import translate
|
3 | 3 |
from link import link
|
4 | 4 |
from binary import write_binary, parse_instructions
|
|
5 |
from preprocess import preprocess
|
5 | 6 |
|
6 | 7 |
def run(args):
|
7 | 8 |
if args.input_file:
|
|
27 | 28 |
|
28 | 29 |
with open(args.output, 'w') as binout:
|
29 | 30 |
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
|
0 | 0 |
def link(glob, funcs, init_code):
|
1 | |
code = []
|
|
1 |
code = [('ldconst', funcs['main'].frame_size), ('call', ('main', 'func'))]
|
2 | 2 |
code.extend(init_code)
|
3 | 3 |
func_locations = {}
|
4 | 4 |
|
|
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 |
}
|