Initial commit

This commit is contained in:
Yoxem 2026-11-23 00:59:40 +08:00
commit d7d13f7840
15 changed files with 1426 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
a.s
a.out
.gitignore

7
Project.toml Normal file
View file

@ -0,0 +1,7 @@
name = "TComp"
uuid = "b858fc1c-1812-4b3c-a2e6-a1a64b2d44f1"
authors = ["Yoxem <yoxem@kianting.info>"]
version = "0.1.0"
[deps]
Match = "7eb4fadd-790c-5f42-8a69-bfa0b872bfbf"

18
README.md Normal file
View file

@ -0,0 +1,18 @@
# TComp
A practice of Essential of Complication in Julia
## Dependencies
- julia
- [Match.jl](github.com/JuliaServices/Match.jl)
## instruction
`./src/TComp.jl [.tc file]`
the output assembly code is `./a.c` in AT&T assembly langauge.
to make it executable, please use `gcc`: `gcc ./a.c -o output.out`
the example `.tc` files is in `./test`
## Known issues
- all connected variable are pathized (I don't understand the tricky method to elimitated the path number)

100
misc/test.jl Normal file
View file

@ -0,0 +1,100 @@
prog1 = ["prm", "+", [7, ["+", [5, 4]]]]
prog2 = ["prm","+", [["prm", "+", [5, 4]], ["prm","+", [7, 8]]]]
prog3 = ["prm","+", [["prm","+", [["cal", "foo", 999], 4]], 7]]
prog4 = ["prm","+", [1, 2]]
prog5 = 5
for i in prog4[2]
println(i)
end
struct SimpleExp
binds
body
end
function rmComplex(exp)
return rmComplexAux1(exp, 0)
end
function rmComplexAux1(exp, varNo)
if exp[1] == "let"
res = splitLet([], exp, varNo)
println("RES=~=~", res)
tup = rmComplexAux2(SimpleExp(res[1], res[2]), res[3])
else
tup = rmComplexAux2(SimpleExp([], exp), varNo)
end
return tup
end
function rmComplexAux2(exp, varNo)
if isa(exp.body, Int) || isa(exp.body, String)
return (exp, varNo)
elseif isa(exp.body, Array) & (exp.body[1] == "prm" || exp.body[1] == "cal")
newResList = exp.binds
new_exp_body = Any[exp.body[1], exp.body[2]]
new_exp_args = []
println("exp_body", exp.body)
for i in exp.body[3]
res = rmComplexAux1(i, varNo)
println("res", res)
varNo = res[2]
newBind = res[1].binds
if newBind != []
println("new~~", newBind)
newResList = vcat(newResList, newBind)
push!(new_exp_args, last(newBind)[2])
else
push!(new_exp_args, i)
end
end
push!(new_exp_body, new_exp_args)
println(newResList)
newBindVar = "tmp" * string(varNo)
varNo += 1
newBind = ["%let", newBindVar, new_exp_body]
push!(newResList, newBind)
return (SimpleExp(newResList, newBindVar), varNo)
else
return (exp, varNo)
end
end
function splitLet(binds, exp, varNo)
if exp[1] == "let"
res = rmComplexAux1(exp[3], varNo)
binds = vcat(binds, res[1].binds)
new_exp = res[1].body
new_bind = ["%let", exp[2], new_exp]
push!(binds, new_bind)
varNo = res[2]
return splitLet(binds, exp[4], varNo)
else
return (binds, exp, varNo)
end
end
prog6 = ["let", "x", ["prm", "-", [10, 3]], ["let", "y", ["cal", "foo", [12]], ["prm", "+", [33, "x"]]]]
println("SPLITLET: ", splitLet([], prog6, 0))
println(rmComplex(prog1), "\n\n")
println(rmComplex(prog2), "\n\n")
println(rmComplex(prog3), "\n\n")
println(rmComplex(prog4), "\n\n")
println(rmComplex(prog5), "\n\n")
println(rmComplex(prog6), "\n\n")

17
passesInstrument.md Normal file
View file

@ -0,0 +1,17 @@
1. **OK**: uniquify deals with the shadowing of variables by renaming every variable to a
unique name.
2. **OK** remove_complex_operands ensures that each subexpression of a primitive operation or
function call is a variable or integer, that is, an atomic expression. We refer
to nonatomic expressions as complex. This pass introduces temporary variables
to hold the results of complex subexpressions.
3. **OK** explicate_control makes the execution order of the program explicit. It converts
the abstract syntax tree representation into a graph in which each node is a
labeled sequence of statements and the edges are goto statements.
4. **OK** select_instructions handles the difference between LVar operations and x86
instructions. This pass converts each LVar operation to a short sequence of
instructions that accomplishes the same task.
assign_homes
5. **OK**assign homes (register allocation)
6. **OK**patch instructions
7. **OK**prelude & conclusion
8. **OK** (vartex coloring)

Binary file not shown.

1
refs/info.txt Normal file
View file

@ -0,0 +1 @@
Source inside the folder is from: https://github.com/IUCompilerCourse/Essentials-of-Compilation

519
src/TComp.jl Normal file
View file

@ -0,0 +1,519 @@
module TComp
include("./parser.jl")
include("./vertexcoloring.jl")
using .Parser
using .VertexColoring
using Match
# For pass 2
struct SimpleExp
binds
body
end
inp = ARGS
f = open(ARGS[1], "r")
prog = read(f, String)
#(prog)
parsed = Parser.totalParse(prog)
println("PARSED\n", Parser.prettyStringLisp(parsed))
tmp_var_no = 0
typeEnv = [
("+", ("Fn", ["int", "int"], "int")),
("-", ("Fn", ["int", "int"], "int")),
("*", ("Fn", ["int", "int"], "int")),
("/", ("Fn", ["int", "int"], "int")),
]
function typeCheck(ast, typeEnv)
pl = Parser.prettyStringLisp
result = @match ast begin
(_, "bool") => "bool"
(_, "int") => "int"
[("%prime", _), (op, _), (lhs, rhs)] => begin
t_lhs = typeCheck(lhs, env)
t_rhs = typeCheck(rhs, env)
actualInputType = [t_lhs, t_rhs]
funcType = findfirst(x->x[1] == op, typeEnv)[2]
expectedInputType = funcType[2]
zipped = zip(expectedInputType, actualInputType)
mapped = map(a -> a[1] && a[2] , zipped)
reduced = reduce((x,y)->x || y, mapped)
if reduced == true
return funcType[3]
else
throw("Type Error: Operands of"
* op * " expected to be"
* string(expectedInputType)
* ", found"
* string(actualInputType))
end
end
(var, "%id") => begin
t_var_id = findfirst(x->x[1] == var, typeEnv)
if t_var_id == nothing
throw(var * "not found in typeEnv")
else
return typeEnv[t_var_id]
end
end
[("%let", _),[(tVar, _), (var_)], exp, body] =>
begin
typeOfExp = typeCheck(exp, typeEnv)
if tVar != typeOfExp
throw("Type Error: type of " * var
* "should be" * tVar
* ", found " * typeOfExp)
else
newTypeEnv = typeEnv
pushfirst!((var, tVar), newTypeEnv)
return typeCheck(body, newTypeEnv)
end
end
[("!", "not"), operand] =>
begin
tOperand = typeCheck(operand, typeEnv)
if tOperand != "bool"
throw("Type Error: type of operands for !"
* "should be" * tVar
* ", found " * typeOfExp)
else
return "bool"
end
end
[(cmp, _), lhs, rhs] where (cmp[2]) in ["==", "!=", "<", "<=", ">", ">=", "&", "|"] =>
begin
tLhs = typeCheck(lhs, typeEnv)
tRhs = typeCheck(rhs, typeEnv)
if !(tLhs == "bool" & tRhs == "bool")
throw("Type Error: operands of"
* cmp * "should be (bool, bool), not"
* string([tLhs, tRhs]))
else
return "bool"
end
end
end
end
# Pass 1: Duplicated varname uniquified
function uniquifyVar(parsed, env)
@match parsed begin
# letrec is not considered
#[("%let", "id"), [ty, var], val, [("%lambda", "id"), args, body]] => nothing
[("%let", "id"), [ty, var], val, body] =>
begin
envNew = env
push!(envNew, var[1]) # push x of var = ("x", "id") in newEnv
res = [("%let", "id"),
[ty, uniquifyVar(var, envNew)],
uniquifyVar(val, env),
uniquifyVar(body, envNew)]
return res
end
(var, "id") =>
begin
reversedEnv = reverse(env)
index = length(env) - findfirst(e -> e == var, reversedEnv) + 1
newVar = var * string(index)
return (newVar, "id")
end
[("%prime", "id"), op, [lhs, rhs]] =>
begin
lhs_new = uniquifyVar(lhs, env)
rhs_new = uniquifyVar(rhs, env)
return [("%prime", "id"), op, [lhs_new, rhs_new]]
end
[("%call", "id"), callee, args...] =>
begin
unifiedCallee = uniquifyVar(callee, env)
unifiedArgs = map(x ->uniquifyVar(x, env), args[1])
return vcat([("%call", "id"), unifiedCallee], [unifiedArgs])
end
(c, "int") => return parsed
_ => "Error"
end
end
# PASS2 explicit Control and Remove Complex
function explicitControlRemoveComplex(prog)
function rmComplex(exp)
return rmComplexAux1(exp, 0)
end
function rmComplexAux1(exp, varNo)
if exp[1] == ("%let", "id")
res = splitLet([], exp, varNo)
tup = rmComplexAux2(SimpleExp(res[1], res[2]), res[3])
else
tup = rmComplexAux2(SimpleExp([], exp), varNo)
end
return tup
end
function rmComplexAux2(exp, varNo)
return @match exp.body begin
(c, "int") => return (exp, varNo)
(v, "id") => return (exp, varNo)
[(id, "id"), caller, callee] where (id == "%prime" || id == "%call") =>
begin
newResList = exp.binds
new_exp_body = Any[(id, "id"), caller]
new_exp_args = []
for i in callee
res = rmComplexAux1(i, varNo)
varNo = res[2]
newBind = res[1].binds
if newBind != []
newResList = vcat(newResList, newBind)
push!(new_exp_args, last(newBind)[2][2])
else
push!(new_exp_args, i)
end
end
push!(new_exp_body, new_exp_args)
newBindVar = [("int", "id"), ("tmp" * string(varNo) , "id")]
varNo += 1
newBind = [("%let", "id"), newBindVar, new_exp_body]
push!(newResList, newBind)
return (SimpleExp(newResList, newBindVar), varNo)
end
_ => "Error"
end
end
function splitLet(binds, exp, varNo)
if exp[1] == ("%let", "id")
res = rmComplexAux1(exp[3], varNo)
binds = vcat(binds, res[1].binds)
new_exp = res[1].body
#fix bug[("int", "id"), ("tmp1", "id")] => ("tmp1", "id")
if new_exp[1] == ("int", "id")
new_exp = new_exp[2]
end
new_bind = [("%let", "id"), exp[2], new_exp]
push!(binds, new_bind)
varNo = res[2]
return splitLet(binds, exp[4], varNo)
else
return (binds, exp, varNo)
end
end
raw_res = rmComplex(prog)[1]
raw_res_body = raw_res.body
#fix bug[("int", "id"), ("tmp1", "id")] => ("tmp1", "id")
if raw_res_body[1] == ("int", "id")
raw_res_body = [("%return", "id"), raw_res_body[2]]
end
if raw_res_body[2] == "int" # ("$8", "int")
raw_res_body = [("%return", "id"), raw_res_body]
end
res = push!(raw_res.binds, raw_res_body)
return res
end
### PASS 3 assign x86 instruction
function assignInstruction(inp)
println("INP", inp)
resList = []
for i in inp
@match i begin
[("%return", "id"), (val, t_val)] => begin
if t_val == "int"
val = "\$" * val
end
push!(resList, ["movq", val, "%rax"])
end
[("%let", "id"), [_ty, (id, "id")],
[("%prime", "id"), (op, _), [(lhs, lhs_t), (rhs, rhs_t)]]] =>
begin
instr = ""
ops = ["+", "-", "*", "/"]
instrs = ["addq", "subq", "imulq", "divq"]
opIndex = findfirst(x -> x == op, ops)
instr = instrs[opIndex]
if lhs_t == "int"
lhs = "\$" * lhs
end
if rhs_t == "int"
rhs = "\$" * rhs
end
if rhs == id
line1 = [instr, lhs, id]
push!(resList, line1)
else
line1 = ["movq", lhs, id]
line2 = [instr, rhs, id]
push!(resList, line1)
push!(resList, line2)
end
#TODO [("%call", "id"), (op, _), args] => ...
end
[("%let", "id"), [_ty, (id, "id")], (val, t_val)] =>
begin
if t_val == "int"
val = "\$" * val
end
line = ["movq", val, id]
push!(resList, line)
end
(c, "int") => push!(resList, ["movq", "\$" * c, "%rax"])
(val, "id") => push!(resList, ["movq", val, "%rax"])
_ => println("Error")
end
end
return resList
end
emptyEnv = []
res = uniquifyVar(parsed, emptyEnv)
#println("PASS1", res)
res2 = explicitControlRemoveComplex(res)
#println("PASS2", Parser.prettyStringLisp(res2))
res3 = assignInstruction(res2)
println("RES3:\n", res3)
# generate vertex graph for register allocation using vertex-coloring model
function generateVertexGraph(prog)
graph = []
progReversed = reverse(prog)
varRegex = r"(^[^\$].*)"
out = Set([])
in_ = Set([])
use = Set([])
def = Set([])
for i in progReversed
use = Set([])
def = Set([])
# only support binary operation(3-term)
out = in_ #prev. out-set becomes current in-set
@match i begin
["movq", orig, dest] => # dest = orig
begin
if match(varRegex, orig) != nothing
push!(use, orig)
end
if match(varRegex, dest) != nothing
push!(def, dest)
end
end
# dest = orig (+-*/) dest
[op, orig, dest] where (op in ["addq", "subq", "imulq", "divq"]) =>
begin
if match(varRegex, orig) != nothing
push!(use, orig)
end
if match(varRegex, dest) != nothing
push!(use, dest)
push!(def, dest)
end
end
_ => 0
end
in_ = union(use, setdiff(out, def))
#println("IN", in_)
#println("DEF", def)
#println("OUT", out)
in_list = collect(in_)
for j in range(1, length(in_list)-1)
for k in range(j+1,length(in_list))
path1 = [in_list[j], in_list[k]]
path2 = [in_list[k], in_list[j]]
if !(path1 in graph) & !(path2 in graph)
push!(graph, path1)
end
end
end
end
return graph
end
vertexGraph = generateVertexGraph(res3)
println(vertexGraph)
colorGraphDictWithMaxId = VertexColoring.vertexColoring(vertexGraph)
colorGraphDict = colorGraphDictWithMaxId[1]
colorMaxId = colorGraphDictWithMaxId[2]
registerList = ["%rax", "%rdx", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15"]
# PASS4 assign home
function assignHomes(inp, colorGraph, registerList)
varRegex = r"(^[^\$%].*)"
res = []
vars = []
for i in inp
orig = i[2]
dest = i[3]
if match(varRegex, orig) != nothing # i.e. orig is a var and not a reg.
if !(orig in vars)
push!(vars, orig)
end
end
if match(varRegex, dest) != nothing # i.e. dest is a var and not a reg.
if !(dest in vars)
push!(vars, dest)
end
end
end
varsLength = length(vars)
for i in inp
instr = i[1]
orig = i[2]
dest = i[3]
if orig in keys(colorGraph)
origColorId = colorGraph[orig]
if origColorId <= length(registerList)
orig = registerList[origColorId]
else
origIdx = findfirst(x -> x == orig,vars)
realAddressIdx = varsLength - origIdx + 1
realAddress = "-$(realAddressIdx * 8)(%rbp)"
orig = realAddress
end
elseif match(r"(^[^\$%].+)", orig) != nothing # isolated (unpathized) variable
orig = "%rax"
end
if dest in keys(colorGraph)
destColorId = colorGraph[dest]
if destColorId <= length(registerList)
dest = registerList[destColorId]
else
destIdx = findfirst(x -> x == dest,vars)
realAddressIdx = varsLength - destIdx + 1
realAddress = "-$(realAddressIdx * 8)(%rbp)"
dest = realAddress
end
elseif match(r"(^[^\$%].+)", dest) != nothing # isolated (unpathized) variable
dest = "%rax"
end
push!(res, [instr, orig, dest])
end
return (res, varsLength)
end
# PASS5 patch instruction (ensure "instr x(rbp) y(rbp)" not happened)
function patchInstruction(inp)
memoryRegex = r".+[(]%rbp[)]$"
res = []
for i in inp
inst = i[1]
orig = i[2]
dest = i[3]
if (match(memoryRegex, orig) != nothing) & (match(memoryRegex, dest) != nothing)
cmd1 = ["movq", orig, "%rax"]
push!(res, cmd1)
cmd2 = [inst, "%rax", dest]
push!(res, cmd2)
elseif (inst == "imulq")
if (match(r"^%.+", dest) == nothing)
cmd1 = ["movq", dest, "%rax"]
cmd2 = ["imulq", orig, "%rax"]
cmd3 = ["movq", "%rax", dest]
push!(res, cmd1)
push!(res, cmd2)
push!(res, cmd3)
else #if dest is a %register
cmd1 = ["imulq", orig, dest] #result stored in %rax
cmd2 = ["movq", "%rax", dest]
push!(res, cmd1)
push!(res, cmd2)
end
else
push!(res, i)
end
end
return res
end
res4 = assignHomes(res3, colorGraphDict, registerList)
res4_prog = res4[1]
varNumber = res4[2]
res5 = patchInstruction(res4_prog)
#println("PASS5",res5)
## PASS6 add prelude and conclude
function preludeConclude(prog, colorMaxId, registerList)
rspSubqMax = (colorMaxId < length(registerList)) ? 0 : ((colorMaxId - length(registerList)) * 8)
body = "start:\n"
for i in prog
ln_cmd = ""
if length(i) == 3
ln_cmd = "\t$(i[1])\t$(i[2]), $(i[3])\n"
body = body * ln_cmd
end
end
body *= "\tjmp\tconclusion\n\n\n"
prelude = """
.globl main
main:
pushq %rbp
movq %rsp, %rbp\n""" * "\tsubq \$$rspSubqMax, %rsp\n\tjmp start\n\n"
conclude = """\nconclusion:\n""" * "\taddq \$$rspSubqMax, %rsp\n\tpopq %rbp\n\tretq\n"
assemblyProg = prelude * body * conclude
return assemblyProg
end
res6 = preludeConclude(res5, colorMaxId, registerList)
# println("PASS6",res6) # emit assembly code
f2 = open("./a.s", "w")
write(f2, res6) #write the assembly code
close(f)
close(f2)
end # module

660
src/parser.jl Normal file
View file

@ -0,0 +1,660 @@
module Parser
using Match
struct ParserResult
matched
pos
txt
end
OptParserResult = Union{Nothing,ParserResult}
struct Psr
fun
end
parserCache = Dict()
function strng(c)
return Psr((txt, pos)-> length(txt) >= pos ?
(txt[pos][1] == c ?
ParserResult(txt[pos], pos+1, txt)
: nothing)
: nothing)
end
function typ(t)
return Psr((txt, pos)-> length(txt) >= pos ?
(txt[pos][2] == t ?
ParserResult(txt[pos], pos+1, txt)
: nothing)
: nothing)
end
(>>)(a::OptParserResult, b::Psr) = then(a, b)
function then(a, b)
if a == nothing
return a
else
key = (objectid(b), a.pos)
if !(key in keys(parserCache))
res = b.fun(a.txt, a.pos)
global parserCache[key] = res
return res
else
return parserCache[key]
end
end
end
(|)(a::Psr, b::Psr) = choice(a, b)
function choice(a, b)
function inner(txt, pos)
aKey = (objectid(a), pos)
if !(aKey in keys(parserCache))
aRes = a.fun(txt, pos)
global parserCache[aKey] = aRes
else
aRes = parserCache[aKey]
end
if a.fun(txt, pos) == nothing
bKey = (objectid(b), pos)
if !(bKey in keys(parserCache))
bRes = b.fun(txt, pos)
global parserCache[bKey] = bRes
else
bRes = parserCache[bKey]
end
return bRes
else
return aRes
end
end
return Psr(inner)
end
function many0(parser)
function many0Aux(txt, pos)
result = []
tmp = parser.fun(txt, pos)
p = pos
while tmp != nothing
p = tmp.pos
result = push!(result, tmp.matched)
tmp = parser.fun(txt, p)
end
return ParserResult(result, p, txt)
end
return Psr(many0Aux)
end
function seq(parserLst)
function seqAux(txt, pos)
result = []
isNothing = false
tmp = nothing
for p in parserLst
tmp = p.fun(txt, pos)
if tmp == nothing
return nothing
else
pos = tmp.pos
result = push!(result, tmp.matched)
end
end
return ParserResult(result, pos, txt)
end
return Psr(seqAux)
end
patternList = [
("if", "if"),
("then", "then"),
("else", "else"),
("True", "bool"),
("False", "bool"),
("cmt", "[#][^\\r\\n]+"),
("int", "\\d+"),
("id", "[_a-zA-Z][_0-9a-zA-Z]*"),
("lParen", "[\\(]"),
("rParen", "[\\)]"),
("eq", "[=][=]"),
("ne", "[!][=]"),
("lt", "[<]"),
("le", "[<][=]"),
("gt", "[>]"),
("ge", "[>][=]"),
("and", "[&]"),
("or", "[\\|]"),
("not", "[!]"),
("plus", "[+]"),
("funType", "[-][\\>]"),
("minus", "[\\-]"),
("mul", "[\\*]"),
("div", "[\\/]"),
("sp", "[\\n\\r ]+"),
("comma", "[,]"),
("semicolon", "[;]"),
("lambda", "[=][\\>]"),
("assign", "[=]"),
]
function combineUnit(tup)
retString = "(?P<" * tup[1] * ">" * tup[2] * ")"
#retStringRegex = Regex(retString)
return retString
end
tmp = join(map(combineUnit, patternList), "|")
matchEachItem = Regex(tmp)
matchAll = "^(" * tmp * ")+\$"
matchEntirely = Regex(matchAll)
#println(matchEntirely)
"""
((int -> int) -> int)
add = (x , y) => x + y;
int a = 8;
12 + foo(13*a,14,15)
"""
function prettyString(ele)
if isa(ele, String)
return "\"" * ele * "\""
elseif isa(ele, Tuple)
mappedEle = map(prettyString, ele)
mappedString = "(" * join(mappedEle, ", ") * ")"
return mappedString
elseif isa(ele, Array)
mappedEle = map(prettyString, ele)
mappedString = "[" * join(mappedEle, ", ") * "]"
return mappedString
elseif isa(ele, ParserResult)
res = "ParserResult(" * prettyString(ele.matched) * "," * prettyString(ele.remained) * ")"
return res
else #number
return string(ele)
end
end
function prettyStringLisp(ele)
if isa(ele, String)
return ele
elseif isa(ele, Tuple)
res = string(prettyStringLisp(ele[1]))
return res
elseif isa(ele, Array)
mappedEle = map(prettyStringLisp, ele)
mappedString = "(" * join(mappedEle, " ") * ")"
return mappedString
elseif isa(ele, ParserResult)
res = prettyStringLisp(ele.matched)
return res
else #number
return string(ele)
end
end
function processKeys(x)
keys_ = keys(x)
return filter((i) -> x[i] != nothing, keys_)[1]
end
#test1 = initWrapped >> strng("123") >> (strng("+")|strng("-"))
#test2 = initWrapped >> seq([strng("123"), strng("+")])
#println(prettyString(test1))
#println(prettyString(test2))
"""
atom = int | id | bool
func = "(" fn_args ")" "=>" body
unit = func | "(" exp ")" | atom
args = unit ("," unit)*
factor = unit "(" args ")"
unary = (-|!) factor | factor
term = (unary (*|/) term) | unary
eqcheckee = (term [(+|-) exp]) | term
logical = eqcheckee ("=="|"<"|"<="|">"|">=") eqcheckee | eqcheckee
subexp = logical ("&&"|"||") logical | logical
exp = if subexp then subexp else subexp | subexp
letexp = ty id "=" exp ";" body
body = exp | letexp
"""
atom = typ("int") | typ("id") | typ("bool")
function fnArgItemAux(input, pos)
rawFunc = seq([typ("comma"), typ("id")])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
matched = rawRes.matched[2]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
fnArgItem = Psr(fnArgItemAux)
function fnArgsAux(input, pos)
rawFunc = seq([typ("id"), many0(fnArgItem)])
res = rawFunc.fun(input, pos)
if res != nothing
matched = vcat([res.matched[1]], res.matched[2])
res = ParserResult(matched, res.pos, res.txt)
return res
else
return nothing
end
end
fnArgs = Psr(fnArgsAux)
function funcAux(input, pos)
rawFunc = seq([typ("lParen"), fnArgs, typ("rParen"), typ("lambda"), body])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
matched = [("%lambda", "id"), rawRes.matched[2], rawRes.matched[5]]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function longUnitAux(input, pos)
rawFunc = seq([typ("lParen"), exp, typ("rParen")])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
#fix for tree fix problem
matched = [("%wrapper", "id"), rawRes.matched[2]]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function unitAux(input, pos)
fun = Psr(funcAux)
longUnit = Psr(longUnitAux)
rawFunc = fun | longUnit | atom
res = rawFunc.fun(input, pos)
return res
end
unit = Psr(unitAux)
function argItemAux(input, pos)
rawFunc = seq([typ("comma"), exp])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
matched = rawRes.matched[2]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
argItem = Psr(argItemAux)
function argsAux(input, pos)
rawFunc = seq([exp, many0(argItem)])
res = rawFunc.fun(input, pos)
if res != nothing
matched = vcat([res.matched[1]], res.matched[2])
res = ParserResult(matched, res.pos, res.txt)
end
return res
end
args = Psr(argsAux)
function longFactorAux(input, pos)
rawFunc = seq([unit, typ("lParen"), args, typ("rParen")])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
matched = [("%call", "id"), rawRes.matched[1], rawRes.matched[3]]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function factorAux(input, pos)
longFactor = Psr(longFactorAux)
rawFunc = longFactor | unit
res = rawFunc.fun(input, pos)
return res
end
factor = Psr(factorAux)
function longUnaryAux(input, pos)
rawFunc = seq([(typ("minus") | typ("not")), factor])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
rator = rawRes.matched[1]
rand = rawRes.matched[2]
if rator[2] == "minus" # -a -> 0 - a
matched = [("%prime", "id"), rator, [("0", "int"), rand]]
else
matched = [rator, rand]
end
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function unaryAux(input, pos)
longUnary = Psr(longUnaryAux)
rawFunc = longUnary | factor
res = rawFunc.fun(input, pos)
return res
end
unary = Psr(unaryAux)
function longTermAux(input, pos)
rawFunc = seq([unary, (typ("mul") | typ("div")), term])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
#correct the tree a /(b / c) -> (a / b) / c
leftRator = rawRes.matched[2]
a = rawRes.matched[1]
bc = rawRes.matched[3]
matched = @match bc begin
[("%prime", "id"), (rightRator, tRightRator), [b, c]] where ((rightRator == "*") || (rightRator == "/")) =>
begin
[("%prime", "id"), (rightRator, tRightRator), [[("%prime", "id"), leftRator, [a, b]], c]]
end
_ => begin
[("%prime", "id"), leftRator, [a, bc]]
end
end
#matched = [("%prime", "id"), leftRator, [a, bc]]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function termAux(input, pos)
longTerm = Psr(longTermAux)
rawFunc = longTerm | unary
res = rawFunc.fun(input, pos)
return res
end
term = Psr(termAux)
function longEqCheckeeAux(input, pos)
rawFunc = seq([term, (typ("plus") | typ("minus")), eqCheckee])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
#correct the tree a -(b - c) -> (a - b) - c
leftRator = rawRes.matched[2]
a = rawRes.matched[1]
bc = rawRes.matched[3]
matched = @match bc begin
[("%prime", "id"), (rightRator, tRightRator), [b, c]] where ((rightRator == "+") || (rightRator == "-")) =>
begin
[("%prime", "id"), (rightRator, tRightRator), [[("%prime", "id"), leftRator, [a, b]], c]]
end
_ => begin
[("%prime", "id"), leftRator, [a, bc]]
end
end
#matched = [("%prime", "id"), leftRator, [a, bc]]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function eqCheckeeAux(input, pos)
longEqCheckee = Psr(longEqCheckeeAux)
rawFunc = longEqCheckee | term
res = rawFunc.fun(input, pos)
return res
end
eqCheckee = Psr(eqCheckeeAux)
function longlogicalAux(input, pos)
rawFunc = seq([eqCheckee, (typ("eq") | typ("ne")|typ("lt") | typ("gt")|typ("le") | typ("ge")), eqCheckee])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
rator = rawRes.matched[2]
l = rawRes.matched[1]
r = rawRes.matched[3]
matched = [rator, l, r]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function logicalAux(input, pos)
longLogical = Psr(longlogicalAux)
rawFunc = longLogical | eqCheckee
res = rawFunc.fun(input, pos)
return res
end
logical = Psr(logicalAux)
function longSubExpAux(input, pos)
rawFunc = seq([logical, (typ("and") | typ("or")), logical])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
rator = rawRes.matched[2]
l = rawRes.matched[1]
r = rawRes.matched[3]
matched = [rator, l, r]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function subExpAux(input, pos)
longSubExp = Psr(longSubExpAux)
rawFunc = longSubExp | logical
res = rawFunc.fun(input, pos)
return res
end
subExp = Psr(subExpAux)
function longExpAux(input, pos)
rawFunc = seq([typ("if"), exp,
typ("then"), body,
typ("else"), body])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
cond = rawRes.matched[2]
branch1 = rawRes.matched[4]
branch2 = rawRes.matched[6]
matched = [("%if", "id"), cond, branch1, branch2]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function expAux(input, pos)
longExp = Psr(longExpAux)
rawFunc = longExp | subExp
res = rawFunc.fun(input, pos)
return res
end
exp = Psr(expAux)
"""tyOfArgs = "(" ty ("," ty)* ")"
tyHead = tyOfArgs | tyOfFn | id
tyOfFn = "(" tyHead -> ty ")"
ty = id | tyOfFn """
function tyArgItemAux(input, pos)
rawFunc = seq([typ("comma"), ty])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
matched = rawRes.matched[2]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function tyOfArgsAux(input, pos)
tyArgItem = Psr(tyArgItemAux)
rawFunc = seq([typ("lParen"), ty, many0(tyArgItem), typ("rParen")])
res = rawFunc.fun(input, pos)
if res != nothing
matched = vcat([("%argType")], vcat([res.matched[2]], res.matched[3]))
res = ParserResult(matched, res.remained)
return res
else
return nothing
end
end
function tyHeadAux(input, pos)
tyOfArgs = Psr(tyOfArgsAux)
tyOfFn = Psr(tyOfFnAux)
rawFunc = tyOfArgs | tyOfFn | typ("id")
res = rawFunc.fun(input, pos)
return res
end
function tyOfFnAux(input, pos)
tyHead = Psr(tyHeadAux)
rawFunc = seq([typ("lParen"), tyHead, typ("funType"), ty, typ("rParen")])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
matched = [("%funType", "id"), rawRes.matched[2], rawRes.matched[4]]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
function tyAux(input, pos)
tyOfFn= Psr(tyOfFnAux)
rawFunc = tyOfFn | typ("id")
res = rawFunc.fun(input, pos)
return res
end
ty = Psr(tyAux)
function letExpAux(input, pos)
#id id "=" exp ";" body
rawFunc = seq([ty, typ("id"), typ("assign"), exp, typ("semicolon"), body])
rawRes = rawFunc.fun(input, pos)
if rawRes != nothing
typ_matched = rawRes.matched[1]
var_matched = rawRes.matched[2]
val_matched = rawRes.matched[4]
body_matched = rawRes.matched[6]
matched = [("%let", "id"), [typ_matched, var_matched], val_matched, body_matched]
res = ParserResult(matched, rawRes.pos, rawRes.txt)
return res
else
return nothing
end
end
letExp = Psr(letExpAux)
function bodyAux(input, pos)
rawFunc = letExp | exp
key = (objectid(rawFunc), pos)
if !(key in keys(parserCache))
res = rawFunc.fun(input, pos)
global parserCache[key] = res
else
res = parserCache[key]
end
return res
end
body = Psr(bodyAux)
function fixTree(item)
return @match item begin
(val, t) => item
[("%wrapper", "id"), inner] => fixTree(inner)
[vars...] => map(fixTree, item)
_ => println("parse Error in fixTree")
end
end
function totalParse(prog)
isEntirelyMatched = match(matchEntirely, prog)
if isEntirelyMatched == false
throw("illegal tokens contained.")
end
mI = eachmatch(matchEachItem, prog)
matchedList = map((x)->x.match, collect(mI))
groupNameList = map(processKeys, collect(mI))
zippedTokenList = collect(zip(matchedList, groupNameList))
withoutSpaceCmt = filter((x)-> (x[2] != "sp") & (x[2] != "cmt"), zippedTokenList)
initWrapped = ParserResult([], 1, withoutSpaceCmt)
res = initWrapped >> body
res2 = fixTree(res.matched)
return res2
end
end

78
src/vertexcoloring.jl Normal file
View file

@ -0,0 +1,78 @@
module VertexColoring
#graph = [['a', 'b'], ['b', 'c'], ['e', 'd'], ['e', 'a'], ['a', 'c'], ['b','e'], ['e','c']]
function vertexColoring(graph)
notDefined = -1
function getColor(v, color)
if !(v in keys(color))
return -1
else
return color[v]
end
end
vertices = Set(vcat(graph...))
verticesList = collect(vertices)
verticesMapping = map(x -> [x, Set()], verticesList)
adjacentNodes = Dict(verticesMapping)
for link in graph
a = link[1]
b = link[2]
push!(adjacentNodes[a], b)
push!(adjacentNodes[b], a)
end
sort!(verticesList, by=x -> length(adjacentNodes[x]), rev=true)
color = Dict()
tmpId = -1
for i in verticesList
i_adjacents = adjacentNodes[i]
i_adjacents_color_set = Set(map(x -> getColor(x, color), collect(i_adjacents)))
i_adjacents_color_list = sort(collect(i_adjacents_color_set))
if i_adjacents_color_list == [notDefined]
color[i] = 2
else
tmpId = 2
for i in i_adjacents_color_list
if tmpId == i
tmpId += 1
end
end
color[i] = tmpId
end
end
maxColorId = tmpId
#force gDict["%rax"] = 1
color["%rax"] = 1
return (color, maxColorId)
end
#println(vertexColoring(graph))
# Disabled = force the color id for %rax set to 1
"""function correctGraph(gDict)
raxOrigId = gDict["%rax"]
for node in keys(gDict)
if gDict[node] == raxOrigId
gDict[node] = 1
elseif gDict[node] == 1
gDict[node] = raxOrigId
end
end
return gDict
end"""
end

3
test/prog.tc Normal file
View file

@ -0,0 +1,3 @@
(int -> int)
addmulti2 = (x , y) => (x + y) * 2;
addmulti2(40,10)

6
test/prog1.tc Normal file
View file

@ -0,0 +1,6 @@
int a = 10;
int a = 13;
int b = (12 + (0 - a));
int c = (14 + b);
int d = 20;
a * 2 + ((b - c) - d)

6
test/prog2.tc Normal file
View file

@ -0,0 +1,6 @@
int a = 10;
int a = 13;
int b = (12 + (0 - a));
int c = (14 + b);
int d = 20;
a - (b - c)

8
test/prog3.tc Normal file
View file

@ -0,0 +1,8 @@
int a = -10;
int a = False;
int b = (12 + (-3));
int c = (14 + b);
int d = 20;
if ((True & a) | False)
then 12
else (if !True then 0 else (d - 3))