import { convertIR } from "./ir/convert"
|
|
import { prettyPrintBlock } from "./ir/pretty"
|
|
import { parse } from "./parser"
|
|
|
|
import type { Attr, Decl, Stmt, Type, VarDecl } from "./ast"
|
|
|
|
type SymbolDefn = {
|
|
attrs: Array<Attr>,
|
|
name: string,
|
|
type: Type
|
|
}
|
|
|
|
type SymbolMap = {
|
|
[name: string]: SymbolDefn
|
|
}
|
|
|
|
// TODO: Support more than one TU
|
|
export const compile = (fileName: string, source: string): string => {
|
|
// 1. Parse
|
|
const ast = parse(source)
|
|
|
|
// 2. Partition declarations and statements
|
|
const decls = ast.filter((x): x is Decl => x.type == "decl")
|
|
const stmts = ast.filter((x): x is Stmt => x.type == "stmt")
|
|
|
|
// 3. Create top-level symbol map
|
|
const symbols = processDecls(decls)
|
|
|
|
// TODO: Support declaring types other than U8/S8
|
|
const asmDecls = Object.values(symbols).map(symbol => `${symbol.name}:: DB`)
|
|
|
|
// TODO: Some form of type-checking
|
|
|
|
// 4. Generate IR
|
|
const ir = convertIR(stmts)
|
|
|
|
console.log("=== IR === ")
|
|
console.log(prettyPrintBlock(ir))
|
|
|
|
// 5. Generate code
|
|
|
|
return ''
|
|
}
|
|
|
|
export const processDecls = (decls: Array<Decl>): SymbolMap => decls.reduce(processDecl, {})
|
|
|
|
export const processDecl = (symbols: SymbolMap, decl: Decl): SymbolMap => {
|
|
const symbol = processVarDecl(symbols, decl)
|
|
|
|
return {
|
|
...symbols,
|
|
[symbol.name]: symbol,
|
|
}
|
|
}
|
|
|
|
export const processVarDecl = (symbols: SymbolMap, decl: VarDecl): SymbolDefn => {
|
|
if (typeof symbols[decl.name] !== 'undefined') {
|
|
throw new Error(`a variable named \`${decl.name}' is already defined`)
|
|
}
|
|
|
|
return {
|
|
attrs: decl.attrs,
|
|
name: decl.name,
|
|
type: decl.args.type,
|
|
}
|
|
}
|