1
Fork 0
master
Joshua Potter 2015-12-15 07:40:18 -05:00
parent 518ca35a68
commit 72f3b2b497
75 changed files with 5203 additions and 5339 deletions

View File

@ -1,5 +1,5 @@
package mJAM;
public class Assembler {
// TBD
// TBD
}

View File

@ -13,297 +13,307 @@ import java.util.SortedSet;
import java.util.TreeSet;
/**
* Disassemble the mJAM object code
* from input file xxx.mJAM
* into output file xxx.asm
* Disassemble the mJAM object code from input file xxx.mJAM into output file
* xxx.asm
*
* @author prins
* @version COMP 520 v2.2
*/
public class Disassembler {
private String objectFileName;
private String asmName;
private FileWriter asmOut;
private boolean error = false;
private Map<Integer, String> addrToLabel;
private String objectFileName;
private String asmName;
private FileWriter asmOut;
private boolean error = false;
private Map<Integer, String> addrToLabel;
public Disassembler(String objectFileName) {
this.objectFileName = objectFileName;
}
public Disassembler(String objectFileName) {
this.objectFileName = objectFileName;
}
/**
* Writes the r-field of an instruction in the form "l<I>reg</I>r", where
* l and r are the bracket characters to use.
* @param leftbracket the character to print before the register.
* @param r the number of the register.
* @param rightbracket the character to print after the register.
*/
private void writeR(char leftbracket, int r, char rightbracket) {
asmWrite(Character.toString(leftbracket));
asmWrite(Machine.intToReg[r].toString());
asmWrite(Character.toString(rightbracket));
}
/**
* Writes the r-field of an instruction in the form "l<I>reg</I>r", where l
* and r are the bracket characters to use.
*
* @param leftbracket
* the character to print before the register.
* @param r
* the number of the register.
* @param rightbracket
* the character to print after the register.
*/
private void writeR(char leftbracket, int r, char rightbracket) {
asmWrite(Character.toString(leftbracket));
asmWrite(Machine.intToReg[r].toString());
asmWrite(Character.toString(rightbracket));
}
/**
* Writes a void n-field of an instruction.
*/
private void blankN() {
asmWrite(" ");
}
/**
* Writes a void n-field of an instruction.
*/
private void blankN() {
asmWrite(" ");
}
// Writes the n-field of an instruction.
/**
* Writes the n-field of an instruction in the form "(n)".
* @param n the integer to write.
*/
private void writeN(int n) {
asmWrite(String.format("%-6s","(" + n + ")"));
}
// Writes the n-field of an instruction.
/**
* Writes the n-field of an instruction in the form "(n)".
*
* @param n
* the integer to write.
*/
private void writeN(int n) {
asmWrite(String.format("%-6s", "(" + n + ")"));
}
/**
* Writes the d-field of an instruction.
* @param d the integer to write.
*/
private void writeD(int d) {
asmWrite(Integer.toString(d));
}
/**
* Writes the d-field of an instruction.
*
* @param d
* the integer to write.
*/
private void writeD(int d) {
asmWrite(Integer.toString(d));
}
/**
* Writes the name of primitive routine with relative address d.
* @param d the displacment of the primitive routine.
*/
private void writePrimitive(int d) {
Machine.Prim prim = Machine.intToPrim[d];
asmWrite(String.format("%-8s",prim.toString()));
}
/**
* Writes the given instruction in assembly-code format.
* @param instr the instruction to display.
*/
private void writeInstruction(Instruction instr) {
/**
* Writes the name of primitive routine with relative address d.
*
* @param d
* the displacment of the primitive routine.
*/
private void writePrimitive(int d) {
Machine.Prim prim = Machine.intToPrim[d];
asmWrite(String.format("%-8s", prim.toString()));
}
String targetLabel = "***";
// get label of destination addr, if instr transfers control
if (instr.r == Machine.Reg.CB.ordinal())
targetLabel = addrToLabel.get(instr.d);
/**
* Writes the given instruction in assembly-code format.
*
* @param instr
* the instruction to display.
*/
private void writeInstruction(Instruction instr) {
Machine.Op instruction = Machine.intToOp[instr.op];
asmWrite(String.format("%-7s",instruction.toString()));
switch (instruction) {
case LOAD:
blankN();
writeD(instr.d);
writeR('[', instr.r, ']');
break;
String targetLabel = "***";
// get label of destination addr, if instr transfers control
if (instr.r == Machine.Reg.CB.ordinal())
targetLabel = addrToLabel.get(instr.d);
case LOADA:
blankN();
writeD(instr.d);
writeR('[', instr.r, ']');
break;
Machine.Op instruction = Machine.intToOp[instr.op];
asmWrite(String.format("%-7s", instruction.toString()));
switch (instruction) {
case LOAD:
blankN();
writeD(instr.d);
writeR('[', instr.r, ']');
break;
case LOADI:
break;
case LOADA:
blankN();
writeD(instr.d);
writeR('[', instr.r, ']');
break;
case LOADL:
blankN();
writeD(instr.d);
break;
case LOADI:
break;
case STORE:
blankN();
writeD(instr.d);
writeR('[', instr.r, ']');
break;
case LOADL:
blankN();
writeD(instr.d);
break;
case STOREI:
break;
case STORE:
blankN();
writeD(instr.d);
writeR('[', instr.r, ']');
break;
case CALL:
if (instr.r == Machine.Reg.PB.ordinal()) {
blankN();
writePrimitive(instr.d);
} else {
blankN();
asmWrite(targetLabel);
}
break;
case STOREI:
break;
case CALLI:
blankN();
asmWrite(targetLabel);
break;
case CALL:
if (instr.r == Machine.Reg.PB.ordinal()) {
blankN();
writePrimitive(instr.d);
} else {
blankN();
asmWrite(targetLabel);
}
break;
case RETURN:
writeN(instr.n);
writeD(instr.d);
break;
case CALLI:
blankN();
asmWrite(targetLabel);
break;
case CALLD:
blankN();
writeD(instr.d);
break;
case RETURN:
writeN(instr.n);
writeD(instr.d);
break;
case PUSH:
blankN();
writeD(instr.d);
break;
case CALLD:
blankN();
writeD(instr.d);
break;
case POP:
blankN();
writeD(instr.d);
break;
case PUSH:
blankN();
writeD(instr.d);
break;
case JUMP:
blankN();
asmWrite(targetLabel);
break;
case POP:
blankN();
writeD(instr.d);
break;
case JUMPI:
break;
case JUMP:
blankN();
asmWrite(targetLabel);
break;
case JUMPIF:
writeN(instr.n);
asmWrite(targetLabel);
break;
case JUMPI:
break;
case HALT:
writeN(instr.n);
break;
case JUMPIF:
writeN(instr.n);
asmWrite(targetLabel);
break;
default:
asmWrite("???? ");
writeN(instr.n);
writeD(instr.d);
writeR('[', instr.r, ']');
break;
}
}
case HALT:
writeN(instr.n);
break;
/**
* disassembles program held in code store
*/
void disassembleProgram(String asmFileName) {
default:
asmWrite("???? ");
writeN(instr.n);
writeD(instr.d);
writeR('[', instr.r, ']');
break;
}
}
try {
asmOut = new FileWriter(asmFileName);
} catch (IOException e) {
System.out.println("Disassembler: can not create asm output file "
+ asmName);
error = true;
return;
}
/**
* disassembles program held in code store
*/
void disassembleProgram(String asmFileName) {
// collect all addresses that may be the target of a jump instruction
SortedSet<Integer> targets = new TreeSet<Integer>();
for (int addr = Machine.CB; addr < Machine.CT; addr++) {
Instruction inst = Machine.code[addr];
Machine.Op op = Machine.intToOp[inst.op];
switch (op) {
case CALL:
case CALLI:
// only consider calls (branches) within code memory (i.e. not primitives)
if (inst.r == Machine.Reg.CB.ordinal())
targets.add(inst.d);
break;
case JUMP:
// address following an unconditional branch is an implicit target
targets.add(addr+1);
targets.add(inst.d);
break;
case JUMPIF:
// a jump of any sort creates a branch target
targets.add(inst.d);
break;
default:
break;
}
}
try {
asmOut = new FileWriter(asmFileName);
} catch (IOException e) {
System.out.println("Disassembler: can not create asm output file " + asmName);
error = true;
return;
}
// map branch target addresses to unique labels
addrToLabel = new HashMap<Integer, String>();
int labelCounter = 10;
for (Integer addr : targets) {
String label = "L" + labelCounter++ ;
addrToLabel.put(addr, label);
}
// collect all addresses that may be the target of a jump instruction
SortedSet<Integer> targets = new TreeSet<Integer>();
for (int addr = Machine.CB; addr < Machine.CT; addr++) {
Instruction inst = Machine.code[addr];
Machine.Op op = Machine.intToOp[inst.op];
switch (op) {
case CALL:
case CALLI:
// only consider calls (branches) within code memory (i.e. not
// primitives)
if (inst.r == Machine.Reg.CB.ordinal())
targets.add(inst.d);
break;
case JUMP:
// address following an unconditional branch is an implicit
// target
targets.add(addr + 1);
targets.add(inst.d);
break;
case JUMPIF:
// a jump of any sort creates a branch target
targets.add(inst.d);
break;
default:
break;
}
}
// disassemble each instruction
for (int addr = Machine.CB; addr < Machine.CT; addr++) {
// generate instruction address
asmWrite(String.format("%3d ", addr));
// map branch target addresses to unique labels
addrToLabel = new HashMap<Integer, String>();
int labelCounter = 10;
for (Integer addr : targets) {
String label = "L" + labelCounter++;
addrToLabel.put(addr, label);
}
// if this addr is a branch target, output label
if (addrToLabel.containsKey(addr))
asmWrite(String.format("%-7s", addrToLabel.get(addr) + ":"));
else
asmWrite(" ");
// disassemble each instruction
for (int addr = Machine.CB; addr < Machine.CT; addr++) {
// instruction
writeInstruction(Machine.code[addr]);
// generate instruction address
asmWrite(String.format("%3d ", addr));
// newline
asmWrite("\n");
}
// if this addr is a branch target, output label
if (addrToLabel.containsKey(addr))
asmWrite(String.format("%-7s", addrToLabel.get(addr) + ":"));
else
asmWrite(" ");
// close output file
try {
asmOut.close();
} catch (IOException e) {
error = true;
}
}
// instruction
writeInstruction(Machine.code[addr]);
private void asmWrite(String s) {
try {
asmOut.write(s);
} catch (IOException e) {
error = true;
}
}
// newline
asmWrite("\n");
}
public static void main(String[] args) {
System.out.println("********** mJAM Disassembler (1.0) **********");
String objectFileName = "obj.mJAM";
if (args.length == 1)
objectFileName = args[0];
Disassembler d = new Disassembler(objectFileName);
d.disassemble();
}
// close output file
try {
asmOut.close();
} catch (IOException e) {
error = true;
}
}
/**
* Disassemble object file
* @return true if error encountered else false
*/
public boolean disassemble() {
ObjectFile objectFile = new ObjectFile(objectFileName);
private void asmWrite(String s) {
try {
asmOut.write(s);
} catch (IOException e) {
error = true;
}
}
// read object file into code store
if (objectFile.read()) {
System.out.println("Disassembler: unable to read object file"
+ objectFileName);
return true;
}
public static void main(String[] args) {
System.out.println("********** mJAM Disassembler (1.0) **********");
String objectFileName = "obj.mJAM";
if (args.length == 1)
objectFileName = args[0];
Disassembler d = new Disassembler(objectFileName);
d.disassemble();
}
// assembler-code output file name
if (objectFileName.endsWith(".mJAM"))
asmName = objectFileName.substring(0, objectFileName.length() - 5)
+ ".asm";
else
asmName = objectFileName + ".asm";
/**
* Disassemble object file
*
* @return true if error encountered else false
*/
public boolean disassemble() {
ObjectFile objectFile = new ObjectFile(objectFileName);
// disassemble to file
disassembleProgram(asmName);
// read object file into code store
if (objectFile.read()) {
System.out.println("Disassembler: unable to read object file" + objectFileName);
return true;
}
if (error) {
System.out.println("Disassembler: unable to write asm file"
+ asmName);
return true;
}
return false;
}
// assembler-code output file name
if (objectFileName.endsWith(".mJAM"))
asmName = objectFileName.substring(0, objectFileName.length() - 5) + ".asm";
else
asmName = objectFileName + ".asm";
// disassemble to file
disassembleProgram(asmName);
if (error) {
System.out.println("Disassembler: unable to write asm file" + asmName);
return true;
}
return false;
}
}

View File

@ -7,30 +7,30 @@ package mJAM;
public class Instruction {
public Instruction() {
op = 0;
r = 0;
n = 0;
d = 0;
}
public Instruction() {
op = 0;
r = 0;
n = 0;
d = 0;
}
public Instruction(int op, int n, int r, int d) {
this.op = op;
this.n = n;
this.r = r;
this.d = d;
}
public Instruction(int op, int n, int r, int d) {
this.op = op;
this.n = n;
this.r = r;
this.d = d;
}
// Java has no type synonyms, so the following representations are
// assumed:
//
// type
// OpCode = 0..15; {4 bits unsigned}
// Register = 0..15; (4 bits unsigned)
// Length = 0..255; {8 bits unsigned}
// Operand = -2147483648 .. +2147483647; (32 bits signed for use with LOADL)
public int op; // OpCode
public int r; // RegisterNumber
public int n; // Length
public int d; // Operand
// Java has no type synonyms, so the following representations are
// assumed:
//
// type
// OpCode = 0..15; {4 bits unsigned}
// Register = 0..15; (4 bits unsigned)
// Length = 0..255; {8 bits unsigned}
// Operand = -2147483648 .. +2147483647; (32 bits signed for use with LOADL)
public int op; // OpCode
public int r; // RegisterNumber
public int n; // Length
public int d; // Operand
}

File diff suppressed because it is too large Load Diff

View File

@ -2,231 +2,188 @@ package mJAM;
/**
* Defines names and sizes of mJAM instructions and primitives
*
* @author prins
* @version COMP 520 V2.2
*/
public final class Machine {
/**
* mJAM instructions
*/
public enum Op {
LOAD,
LOADA,
LOADI,
LOADL,
STORE,
STOREI,
CALL, // direct call of instance method
CALLI, // indirect call of instance method
CALLD, // dynamic call of instance method
RETURN,
PUSH,
POP,
JUMP,
JUMPI,
JUMPIF,
HALT;
}
public static Op [] intToOp = Op.values();
/**
* mJAM registers
*/
public enum Reg {
ZR, // zero, not used
CB, // code base
CT, // code top
CP, // code pointer
PB, // primitives base
PT, // primitives top
SB, // execution stack base
ST, // execution stack top
LB, // locals base
HB, // heap base
HT, // heap top
OB; // object base
}
public static Reg [] intToReg = Reg.values();
/**
* mJAM primitives
*/
public enum Prim {
id,
not,
and,
or,
succ,
pred,
neg,
add,
sub,
mult,
div,
mod,
lt,
le,
ge,
gt,
eq,
ne,
eol,
eof,
get,
put,
geteol,
puteol,
getint,
putint,
putintnl,
alloc,
dispose,
newobj,
newarr,
arrayref,
arrayupd,
fieldref,
fieldupd;
}
public static Prim [] intToPrim = Prim.values();
// range for int constants
public final static long
minintRep = -2147483648,
maxintRep = 2147483647;
// CODE STORE REGISTERS
public final static int CB = 0; // start of code space
public final static int PB = 1024; // size of code space reserved for instructions
public final static int PT = PB + Prim.values().length; // code space reserved for primitives
// CODE STORE
public static Instruction[] code = new Instruction[PB];
public static int CT = CB;
public static void initCodeGen() {
CT = CB;
}
/**
* Places an instruction, with the given fields, into the next position in the code store
* @param op - operation
* @param n - length
* @param r - register
* @param d - displacement
*/
public static void emit(Op op, int n, Reg r, Prim d) {
emit(op.ordinal(), n, r.ordinal(), d.ordinal());
}
/**
* emit operation with single literal argument d (n,r not used). These are
* operations like LOADL 44, PUSH 3, and CALLD 1
*/
public static void emit(Op op, int d) {
emit(op.ordinal(), 0, 0, d);
}
/**
* emit "call primitive operation" (operation built-in to mJAM). This
* generates CALL primitiveop[PB]
*/
public static void emit(Prim d) {
emit(Op.CALL.ordinal(), 0, Machine.Reg.PB.ordinal(), d.ordinal());
}
/**
* emit operations without arguments. These are operations like
* LOADI and STOREI
*/
public static void emit(Op op) {
emit(op, 0, 0, 0);
}
/**
* emit operation with register r and integer displacement. These are
* operations like JUMP 25[CB] and LOAD 6[LB]
*/
public static void emit(Op op, Reg r, int d) {
emit(op.ordinal(), 0, r.ordinal(), d);
}
/**
* emit operation with n field, and register r and integer displacement. These are
* operations like JUMPIF (1) 25[CB]. In the assembly code the value of n is shown
* in parens.
*/
public static void emit(Op op, int n, Reg r, int d) {
emit(op.ordinal(), n, r.ordinal(), d);
}
/**
* emit operation with integer n, r, d. These are operations
* like RETURN (1) 3 and HALT (4) 0. For RETURN the value
* of d is the number of caller args to pop off the callers
* stack and n is the number of values to return at caller stack
* top. n must be 0 or 1.
*/
public static void emit(Op op, int n, int r, int d) {
emit(op.ordinal(), n, r, d);
}
/**
* helper operation for emit using integer values
*/
private static void emit (int op, int n, int r, int d) {
if (n > 255) {
System.out.println("length of operand can't exceed 255 words");
n = 255; // to allow code generation to continue
/**
* mJAM instructions
*/
public enum Op {
LOAD, LOADA, LOADI, LOADL, STORE, STOREI, CALL, // direct call of
// instance method
CALLI, // indirect call of instance method
CALLD, // dynamic call of instance method
RETURN, PUSH, POP, JUMP, JUMPI, JUMPIF, HALT;
}
if (CT >= Machine.PB)
System.out.println("mJAM: code segment capacity exceeded");
Instruction nextInstr = new Instruction(op, n, r, d);
public static Op[] intToOp = Op.values();
/**
* mJAM registers
*/
public enum Reg {
ZR, // zero, not used
CB, // code base
CT, // code top
CP, // code pointer
PB, // primitives base
PT, // primitives top
SB, // execution stack base
ST, // execution stack top
LB, // locals base
HB, // heap base
HT, // heap top
OB; // object base
}
public static Reg[] intToReg = Reg.values();
/**
* mJAM primitives
*/
public enum Prim {
id, not, and, or, succ, pred, neg, add, sub, mult, div, mod, lt, le, ge, gt, eq, ne, eol, eof, get, put, geteol, puteol, getint, putint, putintnl, alloc, dispose, newobj, newarr, arrayref, arrayupd, fieldref, fieldupd;
}
public static Prim[] intToPrim = Prim.values();
// range for int constants
public final static long minintRep = -2147483648, maxintRep = 2147483647;
// CODE STORE REGISTERS
public final static int CB = 0; // start of code space
public final static int PB = 1024; // size of code space reserved for
// instructions
public final static int PT = PB + Prim.values().length; // code space
// reserved for
// primitives
// CODE STORE
public static Instruction[] code = new Instruction[PB];
public static int CT = CB;
public static void initCodeGen() {
CT = CB;
}
/**
* Places an instruction, with the given fields, into the next position in
* the code store
*
* @param op
* - operation
* @param n
* - length
* @param r
* - register
* @param d
* - displacement
*/
public static void emit(Op op, int n, Reg r, Prim d) {
emit(op.ordinal(), n, r.ordinal(), d.ordinal());
}
/**
* emit operation with single literal argument d (n,r not used). These are
* operations like LOADL 44, PUSH 3, and CALLD 1
*/
public static void emit(Op op, int d) {
emit(op.ordinal(), 0, 0, d);
}
/**
* emit "call primitive operation" (operation built-in to mJAM). This
* generates CALL primitiveop[PB]
*/
public static void emit(Prim d) {
emit(Op.CALL.ordinal(), 0, Machine.Reg.PB.ordinal(), d.ordinal());
}
/**
* emit operations without arguments. These are operations like LOADI and
* STOREI
*/
public static void emit(Op op) {
emit(op, 0, 0, 0);
}
/**
* emit operation with register r and integer displacement. These are
* operations like JUMP 25[CB] and LOAD 6[LB]
*/
public static void emit(Op op, Reg r, int d) {
emit(op.ordinal(), 0, r.ordinal(), d);
}
/**
* emit operation with n field, and register r and integer displacement.
* These are operations like JUMPIF (1) 25[CB]. In the assembly code the
* value of n is shown in parens.
*/
public static void emit(Op op, int n, Reg r, int d) {
emit(op.ordinal(), n, r.ordinal(), d);
}
/**
* emit operation with integer n, r, d. These are operations like RETURN (1)
* 3 and HALT (4) 0. For RETURN the value of d is the number of caller args
* to pop off the callers stack and n is the number of values to return at
* caller stack top. n must be 0 or 1.
*/
public static void emit(Op op, int n, int r, int d) {
emit(op.ordinal(), n, r, d);
}
/**
* helper operation for emit using integer values
*/
private static void emit(int op, int n, int r, int d) {
if (n > 255) {
System.out.println("length of operand can't exceed 255 words");
n = 255; // to allow code generation to continue
}
if (CT >= Machine.PB)
System.out.println("mJAM: code segment capacity exceeded");
Instruction nextInstr = new Instruction(op, n, r, d);
Machine.code[CT] = nextInstr;
CT = CT + 1;
}
}
/**
* @return address (relative to CB) of next instruction to be generated
*/
public static int nextInstrAddr() {
return CT;
}
/**
* @return address (relative to CB) of next instruction to be generated
*/
public static int nextInstrAddr() {
return CT;
}
/**
* Update the displacement component of the (JUMP or CALL) instruction at addr
* @param addr
* @param displacement
*/
public static void patch(int addr, int displacement) {
if (addr < 0 || addr >= CT) {
System.out.println("patch: address of instruction to be patched is out of range");
return;
}
if (displacement < 0 || displacement > CT) {
System.out.println("patch: target address of patch is out of range");
return;
}
Machine.code[addr].d = displacement;
return;
}
/**
* Update the displacement component of the (JUMP or CALL) instruction at
* addr
*
* @param addr
* @param displacement
*/
public static void patch(int addr, int displacement) {
if (addr < 0 || addr >= CT) {
System.out.println("patch: address of instruction to be patched is out of range");
return;
}
if (displacement < 0 || displacement > CT) {
System.out.println("patch: target address of patch is out of range");
return;
}
Machine.code[addr].d = displacement;
return;
}
// DATA REPRESENTATION
// DATA REPRESENTATION
public final static int
booleanSize = 1,
characterSize = 1,
integerSize = 1,
addressSize = 1,
linkDataSize = 3 * addressSize, // caller's OB, LB, CP
falseRep = 0,
trueRep = 1,
nullRep = 0;
public final static int booleanSize = 1, characterSize = 1, integerSize = 1, addressSize = 1,
linkDataSize = 3 * addressSize, // caller's OB, LB, CP
falseRep = 0, trueRep = 1, nullRep = 0;
}

View File

@ -11,60 +11,64 @@ import java.io.FileOutputStream;
import java.io.DataOutputStream;
public class ObjectFile {
String objectFileName;
public ObjectFile(String objectFileName) {
super();
this.objectFileName = objectFileName;
}
/**
* Write code store as object file
* @param output object file
* @return true if write fails
*/
public boolean write(){
boolean failed = false;
try {
FileOutputStream objectFile = new FileOutputStream(objectFileName);
DataOutputStream is = new DataOutputStream(objectFile);
for (int i = Machine.CB; i < Machine.CT; i++ ){
Instruction inst = Machine.code[i];
is.writeInt(inst.op);
is.writeInt(inst.n);
is.writeInt(inst.r);
is.writeInt(inst.d);
}
objectFile.close();
}
catch (Exception e) {failed = true;}
return failed;
}
String objectFileName;
/**
* Read object file into code store, setting CT
* @return true if object code read fails
*/
public boolean read() {
boolean failed = false;
try {
FileInputStream objectFile = new FileInputStream(objectFileName);
DataInputStream is = new DataInputStream(objectFile);
Machine.CT = Machine.CB;
while (is.available() > 0 && Machine.CT < Machine.PB){
Instruction inst = new Instruction();
inst.op = is.readInt();
inst.n = is.readInt();
inst.r = is.readInt();
inst.d = is.readInt();
Machine.code[Machine.CT++] = inst;
}
objectFile.close();
} catch (Exception e) {
failed = true;
}
return failed;
}
public ObjectFile(String objectFileName) {
super();
this.objectFileName = objectFileName;
}
/**
* Write code store as object file
*
* @param output
* object file
* @return true if write fails
*/
public boolean write() {
boolean failed = false;
try {
FileOutputStream objectFile = new FileOutputStream(objectFileName);
DataOutputStream is = new DataOutputStream(objectFile);
for (int i = Machine.CB; i < Machine.CT; i++) {
Instruction inst = Machine.code[i];
is.writeInt(inst.op);
is.writeInt(inst.n);
is.writeInt(inst.r);
is.writeInt(inst.d);
}
objectFile.close();
} catch (Exception e) {
failed = true;
}
return failed;
}
/**
* Read object file into code store, setting CT
*
* @return true if object code read fails
*/
public boolean read() {
boolean failed = false;
try {
FileInputStream objectFile = new FileInputStream(objectFileName);
DataInputStream is = new DataInputStream(objectFile);
Machine.CT = Machine.CB;
while (is.available() > 0 && Machine.CT < Machine.PB) {
Instruction inst = new Instruction();
inst.op = is.readInt();
inst.n = is.readInt();
inst.r = is.readInt();
inst.d = is.readInt();
Machine.code[Machine.CT++] = inst;
}
objectFile.close();
} catch (Exception e) {
failed = true;
}
return failed;
}
}

View File

@ -4,154 +4,147 @@
* @version COMP 520 V2.2
*/
package mJAM;
import mJAM.Machine.Op;
import mJAM.Machine.Reg;
import mJAM.Machine.Prim;
// test class to construct and run an mJAM program
public class Test
{
public static void main(String[] args){
Machine.initCodeGen();
System.out.println("Generating test program object code");
/* class A {
* int x;
* int p(){return x;}
* }
*/
Machine.emit(Op.LOADL,11); // hello
Machine.emit(Prim.putintnl);
int patchme_coA = Machine.nextInstrAddr();
Machine.emit(Op.JUMP,Reg.CB,0); // jump around methods of class A (branch to /*coA*/)
// code for p() in A
int label_pA = Machine.nextInstrAddr();
/*pA*/ Machine.emit(Op.LOAD,Reg.OB,0); // x at offset 0 in current instance of A
Machine.emit(Op.HALT,4,0,0);
Machine.emit(Op.RETURN,1,0,0); // return one value, pop zero args
// build class object for A at 0[SB]
int label_coA = Machine.nextInstrAddr();
Machine.patch(patchme_coA, label_coA);
/*coA*/ Machine.emit(Op.LOADL,-1); // no superclass object
Machine.emit(Op.LOADL,1); // number of methods
Machine.emit(Op.LOADA,Reg.CB,label_pA); // code addr of p_A
/* class B extends A {
* int y;
* int p(){return x + 22;}
* }
*/
int patchme_coB = Machine.nextInstrAddr();
Machine.emit(Op.JUMP,Reg.CB,0); // branch around methods in class B
// code for p() in B
int label_pB = Machine.nextInstrAddr();
/*pB*/ Machine.emit(Op.LOAD,Reg.OB,0); // x at offset 0 in current instance
Machine.emit(Op.LOADL,22);
Machine.emit(Op.HALT,4,0,0);
Machine.emit(Prim.add);
Machine.emit(Op.RETURN,1,0,0); // return one value, pop zero args
// build class object for B at 3[SB]
int label_coB = Machine.nextInstrAddr();
Machine.patch(patchme_coB, label_coB);
/*coB*/ Machine.emit(Op.LOADA,Reg.SB,0); // addr of superclass object
Machine.emit(Op.LOADL,1); // number of methods
Machine.emit(Op.LOADA,Reg.CB,label_pB); // code addr of p_B
public class Test {
public static void main(String[] args) {
/* class C {
* public static void main(String [] args) {
* A a = new A();
* a.x = 33;
* System.out.println(a.p());
* ...
*/
int patchme_coC = Machine.nextInstrAddr();
Machine.emit(Op.JUMP,Reg.CB,0); // branch around methods of class C
// code for main() in C
int label_mainC = Machine.nextInstrAddr();
/*mainC*/ Machine.emit(Op.HALT,4,0,0);
// local var "a" will be at 3[LB] after init
Machine.emit(Op.LOADA,Reg.SB,0); // class descriptor for A
Machine.emit(Op.LOADL,1); // size of A
Machine.emit(Prim.newobj); // result addr becomes value of "a"
Machine.emit(Op.LOAD,Reg.LB,3); // value of "a" (heap addr)
Machine.emit(Op.LOADL,0); // "x" is field 0 in A
Machine.emit(Op.LOADL,33); // new value 33
Machine.emit(Op.HALT,4,0,0);
Machine.emit(Prim.fieldupd); // a.x = 33
Machine.emit(Op.LOAD,Reg.LB,3); // addr of instance "a" on heap
Machine.emit(Op.CALLI,Reg.CB,label_pA); // call to known instance method p_A
Machine.emit(Prim.putintnl); // print result
/* ...
* A b = new B();
* b.x = 44;
* System.out.println(b.p());
* } // end main
* } // end class C
*/
// local var "b" will be at 4[LB] after init
Machine.emit(Op.LOADA,Reg.SB,3); // class descriptor for B
Machine.emit(Op.LOADL,2); // size of B
Machine.emit(Prim.newobj); // result addr becomes value of "b"
Machine.emit(Op.LOAD,Reg.LB,4); // fetch b
Machine.emit(Op.LOADL,0); // field 0
Machine.emit(Op.LOADL,44); // b.x = 44
Machine.emit(Prim.fieldupd);
Machine.emit(Op.HALT,4,0,0);
Machine.emit(Op.LOAD,Reg.LB,4); // addr of instance "b"
Machine.emit(Op.CALLD,0); // dynamic call, method index 0 (= method p)
Machine.emit(Prim.putintnl); // print result
Machine.emit(Op.RETURN,0,0,1); // return no value (void), pop 1 arg (= String [] args)
// build class descriptor for C at 6[SB]
int label_coC = Machine.nextInstrAddr();
Machine.patch(patchme_coC, label_coC);
/*coC*/ Machine.emit(Op.LOADL,-1); // no superclass object
Machine.emit(Op.LOADL,0); // number of methods = 0
/*
* End of class declarations - call main
*/
Machine.emit(Op.LOADL,Machine.nullRep); // put null on stack as value of main's arg
Machine.emit(Op.CALL,Reg.CB,label_mainC); // call known static main()
Machine.emit(Op.LOADL,88); // goodbye
Machine.emit(Prim.putintnl);
Machine.emit(Machine.Op.HALT,0,0,0); // halt
Machine.initCodeGen();
System.out.println("Generating test program object code");
/* write code as an object file */
String objectCodeFileName = "test.mJAM";
ObjectFile objF = new ObjectFile(objectCodeFileName);
System.out.print("Writing object code file " + objectCodeFileName + " ... ");
if (objF.write()) {
System.out.println("FAILED!");
return;
}
else
System.out.println("SUCCEEDED");
/* create asm file using disassembler */
String asmCodeFileName = "test.asm";
System.out.print("Writing assembly file ... ");
Disassembler d = new Disassembler(objectCodeFileName);
if (d.disassemble()) {
System.out.println("FAILED!");
return;
}
else
System.out.println("SUCCEEDED");
/* run code */
System.out.println("Running code ... ");
Interpreter.debug(objectCodeFileName, asmCodeFileName);
/*
* class A { int x; int p(){return x;} }
*/
Machine.emit(Op.LOADL, 11); // hello
Machine.emit(Prim.putintnl);
int patchme_coA = Machine.nextInstrAddr();
Machine.emit(Op.JUMP, Reg.CB, 0); // jump around methods of class A
// (branch to /*coA*/)
System.out.println("*** mJAM execution completed");
}
// code for p() in A
int label_pA = Machine.nextInstrAddr();
/* pA */ Machine.emit(Op.LOAD, Reg.OB, 0); // x at offset 0 in current
// instance of A
Machine.emit(Op.HALT, 4, 0, 0);
Machine.emit(Op.RETURN, 1, 0, 0); // return one value, pop zero args
// build class object for A at 0[SB]
int label_coA = Machine.nextInstrAddr();
Machine.patch(patchme_coA, label_coA);
/* coA */ Machine.emit(Op.LOADL, -1); // no superclass object
Machine.emit(Op.LOADL, 1); // number of methods
Machine.emit(Op.LOADA, Reg.CB, label_pA); // code addr of p_A
/*
* class B extends A { int y; int p(){return x + 22;} }
*/
int patchme_coB = Machine.nextInstrAddr();
Machine.emit(Op.JUMP, Reg.CB, 0); // branch around methods in class B
// code for p() in B
int label_pB = Machine.nextInstrAddr();
/* pB */ Machine.emit(Op.LOAD, Reg.OB, 0); // x at offset 0 in current
// instance
Machine.emit(Op.LOADL, 22);
Machine.emit(Op.HALT, 4, 0, 0);
Machine.emit(Prim.add);
Machine.emit(Op.RETURN, 1, 0, 0); // return one value, pop zero args
// build class object for B at 3[SB]
int label_coB = Machine.nextInstrAddr();
Machine.patch(patchme_coB, label_coB);
/* coB */ Machine.emit(Op.LOADA, Reg.SB, 0); // addr of superclass
// object
Machine.emit(Op.LOADL, 1); // number of methods
Machine.emit(Op.LOADA, Reg.CB, label_pB); // code addr of p_B
/*
* class C { public static void main(String [] args) { A a = new A();
* a.x = 33; System.out.println(a.p()); ...
*/
int patchme_coC = Machine.nextInstrAddr();
Machine.emit(Op.JUMP, Reg.CB, 0); // branch around methods of class C
// code for main() in C
int label_mainC = Machine.nextInstrAddr();
/* mainC */ Machine.emit(Op.HALT, 4, 0, 0);
// local var "a" will be at 3[LB] after init
Machine.emit(Op.LOADA, Reg.SB, 0); // class descriptor for A
Machine.emit(Op.LOADL, 1); // size of A
Machine.emit(Prim.newobj); // result addr becomes value of "a"
Machine.emit(Op.LOAD, Reg.LB, 3); // value of "a" (heap addr)
Machine.emit(Op.LOADL, 0); // "x" is field 0 in A
Machine.emit(Op.LOADL, 33); // new value 33
Machine.emit(Op.HALT, 4, 0, 0);
Machine.emit(Prim.fieldupd); // a.x = 33
Machine.emit(Op.LOAD, Reg.LB, 3); // addr of instance "a" on heap
Machine.emit(Op.CALLI, Reg.CB, label_pA); // call to known instance
// method p_A
Machine.emit(Prim.putintnl); // print result
/*
* ... A b = new B(); b.x = 44; System.out.println(b.p()); } // end main
* } // end class C
*/
// local var "b" will be at 4[LB] after init
Machine.emit(Op.LOADA, Reg.SB, 3); // class descriptor for B
Machine.emit(Op.LOADL, 2); // size of B
Machine.emit(Prim.newobj); // result addr becomes value of "b"
Machine.emit(Op.LOAD, Reg.LB, 4); // fetch b
Machine.emit(Op.LOADL, 0); // field 0
Machine.emit(Op.LOADL, 44); // b.x = 44
Machine.emit(Prim.fieldupd);
Machine.emit(Op.HALT, 4, 0, 0);
Machine.emit(Op.LOAD, Reg.LB, 4); // addr of instance "b"
Machine.emit(Op.CALLD, 0); // dynamic call, method index 0 (= method p)
Machine.emit(Prim.putintnl); // print result
Machine.emit(Op.RETURN, 0, 0, 1); // return no value (void), pop 1 arg
// (= String [] args)
// build class descriptor for C at 6[SB]
int label_coC = Machine.nextInstrAddr();
Machine.patch(patchme_coC, label_coC);
/* coC */ Machine.emit(Op.LOADL, -1); // no superclass object
Machine.emit(Op.LOADL, 0); // number of methods = 0
/*
* End of class declarations - call main
*/
Machine.emit(Op.LOADL, Machine.nullRep); // put null on stack as value
// of main's arg
Machine.emit(Op.CALL, Reg.CB, label_mainC); // call known static main()
Machine.emit(Op.LOADL, 88); // goodbye
Machine.emit(Prim.putintnl);
Machine.emit(Machine.Op.HALT, 0, 0, 0); // halt
/* write code as an object file */
String objectCodeFileName = "test.mJAM";
ObjectFile objF = new ObjectFile(objectCodeFileName);
System.out.print("Writing object code file " + objectCodeFileName + " ... ");
if (objF.write()) {
System.out.println("FAILED!");
return;
} else
System.out.println("SUCCEEDED");
/* create asm file using disassembler */
String asmCodeFileName = "test.asm";
System.out.print("Writing assembly file ... ");
Disassembler d = new Disassembler(objectCodeFileName);
if (d.disassemble()) {
System.out.println("FAILED!");
return;
} else
System.out.println("SUCCEEDED");
/* run code */
System.out.println("Running code ... ");
Interpreter.debug(objectCodeFileName, asmCodeFileName);
System.out.println("*** mJAM execution completed");
}
}

View File

@ -9,19 +9,19 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class AST {
public AST(SourcePosition posn) {
this.posn = posn;
}
public AST(SourcePosition posn) {
this.posn = posn;
}
public String toString() {
String fullClassName = this.getClass().getName();
String cn = fullClassName.substring(1 + fullClassName.lastIndexOf('.'));
if (ASTDisplay.showPosition)
cn = cn + " " + posn.toString();
return cn;
}
public String toString() {
String fullClassName = this.getClass().getName();
String cn = fullClassName.substring(1 + fullClassName.lastIndexOf('.'));
if (ASTDisplay.showPosition)
cn = cn + " " + posn.toString();
return cn;
}
public abstract <A, R> R visit(Visitor<A, R> v, A o);
public abstract <A, R> R visit(Visitor<A, R> v, A o);
public SourcePosition posn;
public SourcePosition posn;
}

View File

@ -18,341 +18,339 @@ package miniJava.AbstractSyntaxTrees;
*/
public class ASTDisplay implements Visitor<String, Object> {
public static boolean showPosition = false;
public static boolean showPosition = false;
/**
* print text representation of AST to stdout
*
* @param ast
* root node of AST
*/
public void showTree(AST ast) {
System.out.println("======= AST Display =========================");
ast.visit(this, "");
System.out.println("=============================================");
}
/**
* print text representation of AST to stdout
*
* @param ast
* root node of AST
*/
public void showTree(AST ast) {
System.out.println("======= AST Display =========================");
ast.visit(this, "");
System.out.println("=============================================");
}
// methods to format output
// methods to format output
/**
* display arbitrary text for a node
*
* @param prefix
* spacing to indicate depth in AST
* @param text
* preformatted node display
*/
private void show(String prefix, String text) {
System.out.println(prefix + text);
}
/**
* display arbitrary text for a node
*
* @param prefix
* spacing to indicate depth in AST
* @param text
* preformatted node display
*/
private void show(String prefix, String text) {
System.out.println(prefix + text);
}
/**
* display AST node by name
*
* @param prefix
* spacing to indicate depth in AST
* @param node
* AST node, will be shown by name
*/
private void show(String prefix, AST node) {
System.out.println(prefix + node.toString());
}
/**
* display AST node by name
*
* @param prefix
* spacing to indicate depth in AST
* @param node
* AST node, will be shown by name
*/
private void show(String prefix, AST node) {
System.out.println(prefix + node.toString());
}
/**
* quote a string
*
* @param text
* string to quote
*/
private String quote(String text) {
return ("\"" + text + "\"");
}
/**
* quote a string
*
* @param text
* string to quote
*/
private String quote(String text) {
return ("\"" + text + "\"");
}
/**
* increase depth in AST
*
* @param prefix
* current spacing to indicate depth in AST
* @return new spacing
*/
private String indent(String prefix) {
return prefix + " ";
}
/**
* increase depth in AST
*
* @param prefix
* current spacing to indicate depth in AST
* @return new spacing
*/
private String indent(String prefix) {
return prefix + " ";
}
// /////////////////////////////////////////////////////////////////////////////
//
// PACKAGE
//
// /////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////
//
// PACKAGE
//
// /////////////////////////////////////////////////////////////////////////////
public Object visitPackage(Package prog, String arg) {
show(arg, prog);
ClassDeclList cl = prog.classDeclList;
show(arg, " ClassDeclList [" + cl.size() + "]");
String pfx = arg + " . ";
for (ClassDecl c : prog.classDeclList) {
c.visit(this, pfx);
}
return null;
}
public Object visitPackage(Package prog, String arg) {
show(arg, prog);
ClassDeclList cl = prog.classDeclList;
show(arg, " ClassDeclList [" + cl.size() + "]");
String pfx = arg + " . ";
for (ClassDecl c : prog.classDeclList) {
c.visit(this, pfx);
}
return null;
}
// /////////////////////////////////////////////////////////////////////////////
//
// DECLARATIONS
//
// /////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////
//
// DECLARATIONS
//
// /////////////////////////////////////////////////////////////////////////////
public Object visitClassDecl(ClassDecl clas, String arg) {
show(arg, clas);
show(indent(arg), quote(clas.name) + " classname");
show(arg, " FieldDeclList [" + clas.fieldDeclList.size() + "]");
String pfx = arg + " . ";
for (FieldDecl f : clas.fieldDeclList)
f.visit(this, pfx);
show(arg, " MethodDeclList [" + clas.methodDeclList.size() + "]");
for (MethodDecl m : clas.methodDeclList)
m.visit(this, pfx);
return null;
}
public Object visitClassDecl(ClassDecl clas, String arg) {
show(arg, clas);
show(indent(arg), quote(clas.name) + " classname");
show(arg, " FieldDeclList [" + clas.fieldDeclList.size() + "]");
String pfx = arg + " . ";
for (FieldDecl f : clas.fieldDeclList)
f.visit(this, pfx);
show(arg, " MethodDeclList [" + clas.methodDeclList.size() + "]");
for (MethodDecl m : clas.methodDeclList)
m.visit(this, pfx);
return null;
}
public Object visitFieldDecl(FieldDecl f, String arg) {
show(arg, "(" + (f.isPrivate ? "private" : "public")
+ (f.isStatic ? " static) " : ") ") + f.toString());
f.type.visit(this, indent(arg));
show(indent(arg), quote(f.name) + " fieldname");
return null;
}
public Object visitFieldDecl(FieldDecl f, String arg) {
show(arg, "(" + (f.isPrivate ? "private" : "public") + (f.isStatic ? " static) " : ") ") + f.toString());
f.type.visit(this, indent(arg));
show(indent(arg), quote(f.name) + " fieldname");
return null;
}
public Object visitMethodDecl(MethodDecl m, String arg) {
show(arg, "(" + (m.isPrivate ? "private" : "public")
+ (m.isStatic ? " static) " : ") ") + m.toString());
m.type.visit(this, indent(arg));
show(indent(arg), quote(m.name) + " methodname");
ParameterDeclList pdl = m.parameterDeclList;
show(arg, " ParameterDeclList [" + pdl.size() + "]");
String pfx = ((String) arg) + " . ";
for (ParameterDecl pd : pdl) {
pd.visit(this, pfx);
}
StatementList sl = m.statementList;
show(arg, " StmtList [" + sl.size() + "]");
for (Statement s : sl) {
s.visit(this, pfx);
}
if (m.returnExp != null) {
m.returnExp.visit(this, indent(arg));
}
return null;
}
public Object visitMethodDecl(MethodDecl m, String arg) {
show(arg, "(" + (m.isPrivate ? "private" : "public") + (m.isStatic ? " static) " : ") ") + m.toString());
m.type.visit(this, indent(arg));
show(indent(arg), quote(m.name) + " methodname");
ParameterDeclList pdl = m.parameterDeclList;
show(arg, " ParameterDeclList [" + pdl.size() + "]");
String pfx = ((String) arg) + " . ";
for (ParameterDecl pd : pdl) {
pd.visit(this, pfx);
}
StatementList sl = m.statementList;
show(arg, " StmtList [" + sl.size() + "]");
for (Statement s : sl) {
s.visit(this, pfx);
}
if (m.returnExp != null) {
m.returnExp.visit(this, indent(arg));
}
return null;
}
public Object visitParameterDecl(ParameterDecl pd, String arg) {
show(arg, pd);
pd.type.visit(this, indent(arg));
show(indent(arg), quote(pd.name) + "parametername ");
return null;
}
public Object visitParameterDecl(ParameterDecl pd, String arg) {
show(arg, pd);
pd.type.visit(this, indent(arg));
show(indent(arg), quote(pd.name) + "parametername ");
return null;
}
public Object visitVarDecl(VarDecl vd, String arg) {
show(arg, vd);
vd.type.visit(this, indent(arg));
show(indent(arg), quote(vd.name) + " varname");
return null;
}
public Object visitVarDecl(VarDecl vd, String arg) {
show(arg, vd);
vd.type.visit(this, indent(arg));
show(indent(arg), quote(vd.name) + " varname");
return null;
}
// /////////////////////////////////////////////////////////////////////////////
//
// TYPES
//
// /////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////
//
// TYPES
//
// /////////////////////////////////////////////////////////////////////////////
public Object visitBaseType(BaseType type, String arg) {
show(arg, type.typeKind + " " + type.toString());
return null;
}
public Object visitBaseType(BaseType type, String arg) {
show(arg, type.typeKind + " " + type.toString());
return null;
}
public Object visitClassType(ClassType type, String arg) {
show(arg, type);
show(indent(arg), quote(type.className.spelling) + " classname");
return null;
}
public Object visitClassType(ClassType type, String arg) {
show(arg, type);
show(indent(arg), quote(type.className.spelling) + " classname");
return null;
}
public Object visitArrayType(ArrayType type, String arg) {
show(arg, type);
type.eltType.visit(this, indent(arg));
return null;
}
public Object visitArrayType(ArrayType type, String arg) {
show(arg, type);
type.eltType.visit(this, indent(arg));
return null;
}
// /////////////////////////////////////////////////////////////////////////////
//
// STATEMENTS
//
// /////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////
//
// STATEMENTS
//
// /////////////////////////////////////////////////////////////////////////////
public Object visitBlockStmt(BlockStmt stmt, String arg) {
show(arg, stmt);
StatementList sl = stmt.sl;
show(arg, " StatementList [" + sl.size() + "]");
String pfx = arg + " . ";
for (Statement s : sl) {
s.visit(this, pfx);
}
return null;
}
public Object visitBlockStmt(BlockStmt stmt, String arg) {
show(arg, stmt);
StatementList sl = stmt.sl;
show(arg, " StatementList [" + sl.size() + "]");
String pfx = arg + " . ";
for (Statement s : sl) {
s.visit(this, pfx);
}
return null;
}
public Object visitVardeclStmt(VarDeclStmt stmt, String arg) {
show(arg, stmt);
stmt.varDecl.visit(this, indent(arg));
stmt.initExp.visit(this, indent(arg));
return null;
}
public Object visitVardeclStmt(VarDeclStmt stmt, String arg) {
show(arg, stmt);
stmt.varDecl.visit(this, indent(arg));
stmt.initExp.visit(this, indent(arg));
return null;
}
public Object visitAssignStmt(AssignStmt stmt, String arg) {
show(arg, stmt);
stmt.ref.visit(this, indent(arg));
stmt.val.visit(this, indent(arg));
return null;
}
public Object visitAssignStmt(AssignStmt stmt, String arg) {
show(arg, stmt);
stmt.ref.visit(this, indent(arg));
stmt.val.visit(this, indent(arg));
return null;
}
public Object visitCallStmt(CallStmt stmt, String arg) {
show(arg, stmt);
stmt.methodRef.visit(this, indent(arg));
ExprList al = stmt.argList;
show(arg, " ExprList [" + al.size() + "]");
String pfx = arg + " . ";
for (Expression e : al) {
e.visit(this, pfx);
}
return null;
}
public Object visitCallStmt(CallStmt stmt, String arg) {
show(arg, stmt);
stmt.methodRef.visit(this, indent(arg));
ExprList al = stmt.argList;
show(arg, " ExprList [" + al.size() + "]");
String pfx = arg + " . ";
for (Expression e : al) {
e.visit(this, pfx);
}
return null;
}
public Object visitIfStmt(IfStmt stmt, String arg) {
show(arg, stmt);
stmt.cond.visit(this, indent(arg));
stmt.thenStmt.visit(this, indent(arg));
if (stmt.elseStmt != null)
stmt.elseStmt.visit(this, indent(arg));
return null;
}
public Object visitIfStmt(IfStmt stmt, String arg) {
show(arg, stmt);
stmt.cond.visit(this, indent(arg));
stmt.thenStmt.visit(this, indent(arg));
if (stmt.elseStmt != null)
stmt.elseStmt.visit(this, indent(arg));
return null;
}
public Object visitWhileStmt(WhileStmt stmt, String arg) {
show(arg, stmt);
stmt.cond.visit(this, indent(arg));
stmt.body.visit(this, indent(arg));
return null;
}
public Object visitWhileStmt(WhileStmt stmt, String arg) {
show(arg, stmt);
stmt.cond.visit(this, indent(arg));
stmt.body.visit(this, indent(arg));
return null;
}
// /////////////////////////////////////////////////////////////////////////////
//
// EXPRESSIONS
//
// /////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////
//
// EXPRESSIONS
//
// /////////////////////////////////////////////////////////////////////////////
public Object visitUnaryExpr(UnaryExpr expr, String arg) {
show(arg, expr);
expr.operator.visit(this, indent(arg));
expr.expr.visit(this, indent(indent(arg)));
return null;
}
public Object visitUnaryExpr(UnaryExpr expr, String arg) {
show(arg, expr);
expr.operator.visit(this, indent(arg));
expr.expr.visit(this, indent(indent(arg)));
return null;
}
public Object visitBinaryExpr(BinaryExpr expr, String arg) {
show(arg, expr);
expr.operator.visit(this, indent(arg));
expr.left.visit(this, indent(indent(arg)));
expr.right.visit(this, indent(indent(arg)));
return null;
}
public Object visitBinaryExpr(BinaryExpr expr, String arg) {
show(arg, expr);
expr.operator.visit(this, indent(arg));
expr.left.visit(this, indent(indent(arg)));
expr.right.visit(this, indent(indent(arg)));
return null;
}
public Object visitRefExpr(RefExpr expr, String arg) {
show(arg, expr);
expr.ref.visit(this, indent(arg));
return null;
}
public Object visitRefExpr(RefExpr expr, String arg) {
show(arg, expr);
expr.ref.visit(this, indent(arg));
return null;
}
public Object visitCallExpr(CallExpr expr, String arg) {
show(arg, expr);
expr.functionRef.visit(this, indent(arg));
ExprList al = expr.argList;
show(arg, " ExprList + [" + al.size() + "]");
String pfx = arg + " . ";
for (Expression e : al) {
e.visit(this, pfx);
}
return null;
}
public Object visitCallExpr(CallExpr expr, String arg) {
show(arg, expr);
expr.functionRef.visit(this, indent(arg));
ExprList al = expr.argList;
show(arg, " ExprList + [" + al.size() + "]");
String pfx = arg + " . ";
for (Expression e : al) {
e.visit(this, pfx);
}
return null;
}
public Object visitLiteralExpr(LiteralExpr expr, String arg) {
show(arg, expr);
expr.literal.visit(this, indent(arg));
return null;
}
public Object visitLiteralExpr(LiteralExpr expr, String arg) {
show(arg, expr);
expr.literal.visit(this, indent(arg));
return null;
}
public Object visitNewArrayExpr(NewArrayExpr expr, String arg) {
show(arg, expr);
expr.eltType.visit(this, indent(arg));
expr.sizeExpr.visit(this, indent(arg));
return null;
}
public Object visitNewArrayExpr(NewArrayExpr expr, String arg) {
show(arg, expr);
expr.eltType.visit(this, indent(arg));
expr.sizeExpr.visit(this, indent(arg));
return null;
}
public Object visitNewObjectExpr(NewObjectExpr expr, String arg) {
show(arg, expr);
expr.classtype.visit(this, indent(arg));
return null;
}
public Object visitNewObjectExpr(NewObjectExpr expr, String arg) {
show(arg, expr);
expr.classtype.visit(this, indent(arg));
return null;
}
// /////////////////////////////////////////////////////////////////////////////
//
// REFERENCES
//
// /////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////
//
// REFERENCES
//
// /////////////////////////////////////////////////////////////////////////////
public Object visitQualifiedRef(QualifiedRef qr, String arg) {
show(arg, qr);
qr.id.visit(this, indent(arg));
qr.ref.visit(this, indent(arg));
return null;
}
public Object visitQualifiedRef(QualifiedRef qr, String arg) {
show(arg, qr);
qr.id.visit(this, indent(arg));
qr.ref.visit(this, indent(arg));
return null;
}
public Object visitIndexedRef(IndexedRef ir, String arg) {
show(arg, ir);
ir.indexExpr.visit(this, indent(arg));
ir.ref.visit(this, indent(arg));
return null;
}
public Object visitIndexedRef(IndexedRef ir, String arg) {
show(arg, ir);
ir.indexExpr.visit(this, indent(arg));
ir.ref.visit(this, indent(arg));
return null;
}
public Object visitIdRef(IdRef ref, String arg) {
show(arg, ref);
ref.id.visit(this, indent(arg));
return null;
}
public Object visitIdRef(IdRef ref, String arg) {
show(arg, ref);
ref.id.visit(this, indent(arg));
return null;
}
public Object visitThisRef(ThisRef ref, String arg) {
show(arg, ref);
return null;
}
public Object visitThisRef(ThisRef ref, String arg) {
show(arg, ref);
return null;
}
// /////////////////////////////////////////////////////////////////////////////
//
// TERMINALS
//
// /////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////
//
// TERMINALS
//
// /////////////////////////////////////////////////////////////////////////////
public Object visitIdentifier(Identifier id, String arg) {
show(arg, quote(id.spelling) + " " + id.toString());
return null;
}
public Object visitIdentifier(Identifier id, String arg) {
show(arg, quote(id.spelling) + " " + id.toString());
return null;
}
public Object visitOperator(Operator op, String arg) {
show(arg, quote(op.spelling) + " " + op.toString());
return null;
}
public Object visitOperator(Operator op, String arg) {
show(arg, quote(op.spelling) + " " + op.toString());
return null;
}
public Object visitIntLiteral(IntLiteral num, String arg) {
show(arg, quote(num.spelling) + " " + num.toString());
return null;
}
public Object visitIntLiteral(IntLiteral num, String arg) {
show(arg, quote(num.spelling) + " " + num.toString());
return null;
}
public Object visitBooleanLiteral(BooleanLiteral bool, String arg) {
show(arg, quote(bool.spelling) + " " + bool.toString());
return null;
}
public Object visitBooleanLiteral(BooleanLiteral bool, String arg) {
show(arg, quote(bool.spelling) + " " + bool.toString());
return null;
}
}

View File

@ -10,18 +10,18 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class ArrayType extends Type {
public ArrayType(Type eltType, SourcePosition posn) {
super(TypeKind.ARRAY, posn);
this.eltType = eltType;
}
public ArrayType(Type eltType, SourcePosition posn) {
super(TypeKind.ARRAY, posn);
this.eltType = eltType;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitArrayType(this, o);
}
public String toString() {
return eltType + " Array";
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitArrayType(this, o);
}
public Type eltType;
public String toString() {
return eltType + " Array";
}
public Type eltType;
}

View File

@ -8,16 +8,16 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class AssignStmt extends Statement {
public AssignStmt(Reference r, Expression e, SourcePosition posn) {
super(posn);
ref = r;
val = e;
}
public AssignStmt(Reference r, Expression e, SourcePosition posn) {
super(posn);
ref = r;
val = e;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitAssignStmt(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitAssignStmt(this, o);
}
public Reference ref;
public Expression val;
public Reference ref;
public Expression val;
}

View File

@ -8,15 +8,15 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class BaseType extends Type {
public BaseType(TypeKind t, SourcePosition posn) {
super(t, posn);
}
public BaseType(TypeKind t, SourcePosition posn) {
super(t, posn);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitBaseType(this, o);
}
public String toString() {
return typeKind.toString();
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitBaseType(this, o);
}
public String toString() {
return typeKind.toString();
}
}

View File

@ -8,19 +8,18 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class BinaryExpr extends Expression {
public BinaryExpr(Operator o, Expression e1, Expression e2,
SourcePosition posn) {
super(posn);
operator = o;
left = e1;
right = e2;
}
public BinaryExpr(Operator o, Expression e1, Expression e2, SourcePosition posn) {
super(posn);
operator = o;
left = e1;
right = e2;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitBinaryExpr(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitBinaryExpr(this, o);
}
public Operator operator;
public Expression left;
public Expression right;
public Operator operator;
public Expression left;
public Expression right;
}

View File

@ -8,14 +8,14 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class BlockStmt extends Statement {
public BlockStmt(StatementList sl, SourcePosition posn) {
super(posn);
this.sl = sl;
}
public BlockStmt(StatementList sl, SourcePosition posn) {
super(posn);
this.sl = sl;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitBlockStmt(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitBlockStmt(this, o);
}
public StatementList sl;
public StatementList sl;
}

View File

@ -9,11 +9,11 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class BooleanLiteral extends Literal {
public BooleanLiteral(String spelling, SourcePosition posn) {
super(spelling, posn);
}
public BooleanLiteral(String spelling, SourcePosition posn) {
super(spelling, posn);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitBooleanLiteral(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitBooleanLiteral(this, o);
}
}

View File

@ -8,16 +8,16 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class CallExpr extends Expression {
public CallExpr(Reference f, ExprList el, SourcePosition posn) {
super(posn);
functionRef = f;
argList = el;
}
public CallExpr(Reference f, ExprList el, SourcePosition posn) {
super(posn);
functionRef = f;
argList = el;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitCallExpr(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitCallExpr(this, o);
}
public Reference functionRef;
public ExprList argList;
public Reference functionRef;
public ExprList argList;
}

View File

@ -8,16 +8,16 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class CallStmt extends Statement {
public CallStmt(Reference m, ExprList el, SourcePosition posn) {
super(posn);
methodRef = m;
argList = el;
}
public CallStmt(Reference m, ExprList el, SourcePosition posn) {
super(posn);
methodRef = m;
argList = el;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitCallStmt(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitCallStmt(this, o);
}
public Reference methodRef;
public ExprList argList;
public Reference methodRef;
public ExprList argList;
}

View File

@ -9,17 +9,16 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class ClassDecl extends Declaration {
public ClassDecl(String cn, FieldDeclList fdl, MethodDeclList mdl,
SourcePosition posn) {
super(cn, null, posn);
fieldDeclList = fdl;
methodDeclList = mdl;
}
public ClassDecl(String cn, FieldDeclList fdl, MethodDeclList mdl, SourcePosition posn) {
super(cn, null, posn);
fieldDeclList = fdl;
methodDeclList = mdl;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitClassDecl(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitClassDecl(this, o);
}
public FieldDeclList fieldDeclList;
public MethodDeclList methodDeclList;
public FieldDeclList fieldDeclList;
public MethodDeclList methodDeclList;
}

View File

@ -8,25 +8,25 @@ package miniJava.AbstractSyntaxTrees;
import java.util.*;
public class ClassDeclList implements Iterable<ClassDecl> {
public ClassDeclList() {
classDeclList = new ArrayList<ClassDecl>();
}
public ClassDeclList() {
classDeclList = new ArrayList<ClassDecl>();
}
public void add(ClassDecl cd) {
classDeclList.add(cd);
}
public void add(ClassDecl cd) {
classDeclList.add(cd);
}
public ClassDecl get(int i) {
return classDeclList.get(i);
}
public ClassDecl get(int i) {
return classDeclList.get(i);
}
public int size() {
return classDeclList.size();
}
public int size() {
return classDeclList.size();
}
public Iterator<ClassDecl> iterator() {
return classDeclList.iterator();
}
public Iterator<ClassDecl> iterator() {
return classDeclList.iterator();
}
private List<ClassDecl> classDeclList;
private List<ClassDecl> classDeclList;
}

View File

@ -8,18 +8,18 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class ClassType extends Type {
public ClassType(Identifier cn, SourcePosition posn) {
super(TypeKind.CLASS, posn);
className = cn;
}
public ClassType(Identifier cn, SourcePosition posn) {
super(TypeKind.CLASS, posn);
className = cn;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitClassType(this, o);
}
public String toString() {
return "Class " + className.spelling;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitClassType(this, o);
}
public Identifier className;
public String toString() {
return "Class " + className.spelling;
}
public Identifier className;
}

View File

@ -11,14 +11,14 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class Declaration extends AST {
public Declaration(String name, Type type, SourcePosition posn) {
super(posn);
this.name = name;
this.type = type;
}
public Declaration(String name, Type type, SourcePosition posn) {
super(posn);
this.name = name;
this.type = type;
}
public RuntimeEntity entity;
public IdTable table;
public String name;
public Type type;
public RuntimeEntity entity;
public IdTable table;
public String name;
public Type type;
}

View File

@ -8,16 +8,15 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
*/
public class Declarators {
public Declarators(boolean isPrivate, boolean isStatic, Type mt,
SourcePosition posn) {
this.isPrivate = isPrivate;
this.isStatic = isStatic;
this.mt = mt;
this.posn = posn;
}
public Declarators(boolean isPrivate, boolean isStatic, Type mt, SourcePosition posn) {
this.isPrivate = isPrivate;
this.isStatic = isStatic;
this.mt = mt;
this.posn = posn;
}
public boolean isPrivate;
public boolean isStatic;
public Type mt;
public SourcePosition posn;
public boolean isPrivate;
public boolean isStatic;
public Type mt;
public SourcePosition posn;
}

View File

@ -8,25 +8,25 @@ package miniJava.AbstractSyntaxTrees;
import java.util.*;
public class ExprList implements Iterable<Expression> {
public ExprList() {
elist = new ArrayList<Expression>();
}
public ExprList() {
elist = new ArrayList<Expression>();
}
public void add(Expression e) {
elist.add(e);
}
public void add(Expression e) {
elist.add(e);
}
public Expression get(int i) {
return elist.get(i);
}
public Expression get(int i) {
return elist.get(i);
}
public int size() {
return elist.size();
}
public int size() {
return elist.size();
}
public Iterator<Expression> iterator() {
return elist.iterator();
}
public Iterator<Expression> iterator() {
return elist.iterator();
}
private List<Expression> elist;
private List<Expression> elist;
}

View File

@ -9,8 +9,8 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class Expression extends AST {
public Expression(SourcePosition posn) {
super(posn);
}
public Expression(SourcePosition posn) {
super(posn);
}
}

View File

@ -9,20 +9,19 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class FieldDecl extends MemberDecl {
public FieldDecl(boolean isPrivate, boolean isStatic, Type t, String name,
SourcePosition posn) {
super(isPrivate, isStatic, t, name, posn);
}
public FieldDecl(boolean isPrivate, boolean isStatic, Type t, String name, SourcePosition posn) {
super(isPrivate, isStatic, t, name, posn);
}
public FieldDecl(MemberDecl md, SourcePosition posn) {
super(md, posn);
}
public FieldDecl(MemberDecl md, SourcePosition posn) {
super(md, posn);
}
public FieldDecl(Declarators d, String name) {
super(d.isPrivate, d.isStatic, d.mt, name, d.posn);
}
public FieldDecl(Declarators d, String name) {
super(d.isPrivate, d.isStatic, d.mt, name, d.posn);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitFieldDecl(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitFieldDecl(this, o);
}
}

View File

@ -8,25 +8,25 @@ package miniJava.AbstractSyntaxTrees;
import java.util.*;
public class FieldDeclList implements Iterable<FieldDecl> {
public FieldDeclList() {
fieldDeclList = new ArrayList<FieldDecl>();
}
public FieldDeclList() {
fieldDeclList = new ArrayList<FieldDecl>();
}
public void add(FieldDecl cd) {
fieldDeclList.add(cd);
}
public void add(FieldDecl cd) {
fieldDeclList.add(cd);
}
public FieldDecl get(int i) {
return fieldDeclList.get(i);
}
public FieldDecl get(int i) {
return fieldDeclList.get(i);
}
public int size() {
return fieldDeclList.size();
}
public int size() {
return fieldDeclList.size();
}
public Iterator<FieldDecl> iterator() {
return fieldDeclList.iterator();
}
public Iterator<FieldDecl> iterator() {
return fieldDeclList.iterator();
}
private List<FieldDecl> fieldDeclList;
private List<FieldDecl> fieldDeclList;
}

View File

@ -9,14 +9,14 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class IdRef extends Reference {
public IdRef(Identifier id, SourcePosition posn) {
super(posn);
this.id = id;
}
public IdRef(Identifier id, SourcePosition posn) {
super(posn);
this.id = id;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIdRef(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIdRef(this, o);
}
public Identifier id;
public Identifier id;
}

View File

@ -10,14 +10,14 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class Identifier extends Terminal {
public Identifier(String s, SourcePosition posn) {
super(s, posn);
}
public Identifier(String s, SourcePosition posn) {
super(s, posn);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIdentifier(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIdentifier(this, o);
}
public Declaration decl;
public RuntimeEntity entity;
public Declaration decl;
public RuntimeEntity entity;
}

View File

@ -8,25 +8,25 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class IfStmt extends Statement {
public IfStmt(Expression b, Statement t, Statement e, SourcePosition posn) {
super(posn);
cond = b;
thenStmt = t;
elseStmt = e;
}
public IfStmt(Expression b, Statement t, Statement e, SourcePosition posn) {
super(posn);
cond = b;
thenStmt = t;
elseStmt = e;
}
public IfStmt(Expression b, Statement t, SourcePosition posn) {
super(posn);
cond = b;
thenStmt = t;
elseStmt = null;
}
public IfStmt(Expression b, Statement t, SourcePosition posn) {
super(posn);
cond = b;
thenStmt = t;
elseStmt = null;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIfStmt(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIfStmt(this, o);
}
public Expression cond;
public Statement thenStmt;
public Statement elseStmt;
public Expression cond;
public Statement thenStmt;
public Statement elseStmt;
}

View File

@ -9,16 +9,16 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class IndexedRef extends Reference {
public IndexedRef(Reference ref, Expression expr, SourcePosition posn) {
super(posn);
this.ref = ref;
this.indexExpr = expr;
}
public IndexedRef(Reference ref, Expression expr, SourcePosition posn) {
super(posn);
this.ref = ref;
this.indexExpr = expr;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIndexedRef(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIndexedRef(this, o);
}
public Reference ref;
public Expression indexExpr;
public Reference ref;
public Expression indexExpr;
}

View File

@ -9,11 +9,11 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class IntLiteral extends Literal {
public IntLiteral(String s, SourcePosition posn) {
super(s, posn);
}
public IntLiteral(String s, SourcePosition posn) {
super(s, posn);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIntLiteral(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitIntLiteral(this, o);
}
}

View File

@ -9,7 +9,7 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class Literal extends Terminal {
public Literal(String spelling, SourcePosition posn) {
super(spelling, posn);
}
public Literal(String spelling, SourcePosition posn) {
super(spelling, posn);
}
}

View File

@ -8,14 +8,14 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class LiteralExpr extends Expression {
public LiteralExpr(Literal c, SourcePosition posn) {
super(posn);
literal = c;
}
public LiteralExpr(Literal c, SourcePosition posn) {
super(posn);
literal = c;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitLiteralExpr(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitLiteralExpr(this, o);
}
public Literal literal;
public Literal literal;
}

View File

@ -9,8 +9,8 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class LocalDecl extends Declaration {
public LocalDecl(String name, Type t, SourcePosition posn) {
super(name, t, posn);
}
public LocalDecl(String name, Type t, SourcePosition posn) {
super(name, t, posn);
}
}

View File

@ -9,19 +9,18 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
abstract public class MemberDecl extends Declaration {
public MemberDecl(boolean isPrivate, boolean isStatic, Type mt,
String name, SourcePosition posn) {
super(name, mt, posn);
this.isPrivate = isPrivate;
this.isStatic = isStatic;
}
public MemberDecl(boolean isPrivate, boolean isStatic, Type mt, String name, SourcePosition posn) {
super(name, mt, posn);
this.isPrivate = isPrivate;
this.isStatic = isStatic;
}
public MemberDecl(MemberDecl md, SourcePosition posn) {
super(md.name, md.type, posn);
this.isPrivate = md.isPrivate;
this.isStatic = md.isStatic;
}
public MemberDecl(MemberDecl md, SourcePosition posn) {
super(md.name, md.type, posn);
this.isPrivate = md.isPrivate;
this.isStatic = md.isStatic;
}
public boolean isPrivate;
public boolean isStatic;
public boolean isPrivate;
public boolean isStatic;
}

View File

@ -9,19 +9,18 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class MethodDecl extends MemberDecl {
public MethodDecl(MemberDecl md, ParameterDeclList pl, StatementList sl,
Expression e, SourcePosition posn) {
super(md, posn);
parameterDeclList = pl;
statementList = sl;
returnExp = e;
}
public MethodDecl(MemberDecl md, ParameterDeclList pl, StatementList sl, Expression e, SourcePosition posn) {
super(md, posn);
parameterDeclList = pl;
statementList = sl;
returnExp = e;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitMethodDecl(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitMethodDecl(this, o);
}
public ParameterDeclList parameterDeclList;
public StatementList statementList;
public Expression returnExp;
public ParameterDeclList parameterDeclList;
public StatementList statementList;
public Expression returnExp;
}

View File

@ -8,25 +8,25 @@ package miniJava.AbstractSyntaxTrees;
import java.util.*;
public class MethodDeclList implements Iterable<MethodDecl> {
public MethodDeclList() {
methodDeclList = new ArrayList<MethodDecl>();
}
public MethodDeclList() {
methodDeclList = new ArrayList<MethodDecl>();
}
public void add(MethodDecl cd) {
methodDeclList.add(cd);
}
public void add(MethodDecl cd) {
methodDeclList.add(cd);
}
public MethodDecl get(int i) {
return methodDeclList.get(i);
}
public MethodDecl get(int i) {
return methodDeclList.get(i);
}
public int size() {
return methodDeclList.size();
}
public int size() {
return methodDeclList.size();
}
public Iterator<MethodDecl> iterator() {
return methodDeclList.iterator();
}
public Iterator<MethodDecl> iterator() {
return methodDeclList.iterator();
}
private List<MethodDecl> methodDeclList;
private List<MethodDecl> methodDeclList;
}

View File

@ -8,16 +8,16 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class NewArrayExpr extends NewExpr {
public NewArrayExpr(Type et, Expression e, SourcePosition posn) {
super(posn);
eltType = et;
sizeExpr = e;
}
public NewArrayExpr(Type et, Expression e, SourcePosition posn) {
super(posn);
eltType = et;
sizeExpr = e;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitNewArrayExpr(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitNewArrayExpr(this, o);
}
public Type eltType;
public Expression sizeExpr;
public Type eltType;
public Expression sizeExpr;
}

View File

@ -9,7 +9,7 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class NewExpr extends Expression {
public NewExpr(SourcePosition posn) {
super(posn);
}
public NewExpr(SourcePosition posn) {
super(posn);
}
}

View File

@ -8,14 +8,14 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class NewObjectExpr extends NewExpr {
public NewObjectExpr(ClassType ct, SourcePosition posn) {
super(posn);
classtype = ct;
}
public NewObjectExpr(ClassType ct, SourcePosition posn) {
super(posn);
classtype = ct;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitNewObjectExpr(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitNewObjectExpr(this, o);
}
public ClassType classtype;
public ClassType classtype;
}

View File

@ -10,13 +10,13 @@ import miniJava.SyntacticAnalyzer.Token;
public class Operator extends Terminal {
public Operator(Token t, SourcePosition posn) {
super(t.spelling, posn);
}
public Operator(Token t, SourcePosition posn) {
super(t.spelling, posn);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitOperator(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitOperator(this, o);
}
public Token token;
public Token token;
}

View File

@ -9,14 +9,14 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class Package extends AST {
public Package(ClassDeclList cdl, SourcePosition posn) {
super(posn);
classDeclList = cdl;
}
public Package(ClassDeclList cdl, SourcePosition posn) {
super(posn);
classDeclList = cdl;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitPackage(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitPackage(this, o);
}
public ClassDeclList classDeclList;
public ClassDeclList classDeclList;
}

View File

@ -9,11 +9,11 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class ParameterDecl extends LocalDecl {
public ParameterDecl(Type t, String name, SourcePosition posn) {
super(name, t, posn);
}
public ParameterDecl(Type t, String name, SourcePosition posn) {
super(name, t, posn);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitParameterDecl(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitParameterDecl(this, o);
}
}

View File

@ -8,25 +8,25 @@ package miniJava.AbstractSyntaxTrees;
import java.util.*;
public class ParameterDeclList implements Iterable<ParameterDecl> {
public ParameterDeclList() {
parameterDeclList = new ArrayList<ParameterDecl>();
}
public ParameterDeclList() {
parameterDeclList = new ArrayList<ParameterDecl>();
}
public void add(ParameterDecl s) {
parameterDeclList.add(s);
}
public void add(ParameterDecl s) {
parameterDeclList.add(s);
}
public ParameterDecl get(int i) {
return parameterDeclList.get(i);
}
public ParameterDecl get(int i) {
return parameterDeclList.get(i);
}
public int size() {
return parameterDeclList.size();
}
public int size() {
return parameterDeclList.size();
}
public Iterator<ParameterDecl> iterator() {
return parameterDeclList.iterator();
}
public Iterator<ParameterDecl> iterator() {
return parameterDeclList.iterator();
}
private List<ParameterDecl> parameterDeclList;
private List<ParameterDecl> parameterDeclList;
}

View File

@ -9,17 +9,17 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class QualifiedRef extends Reference {
public QualifiedRef(Reference ref, Identifier id, SourcePosition posn) {
super(posn);
this.ref = ref;
this.id = id;
}
public QualifiedRef(Reference ref, Identifier id, SourcePosition posn) {
super(posn);
this.ref = ref;
this.id = id;
}
@Override
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitQualifiedRef(this, o);
}
@Override
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitQualifiedRef(this, o);
}
public Reference ref;
public Identifier id;
public Reference ref;
public Identifier id;
}

View File

@ -8,14 +8,14 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class RefExpr extends Expression {
public RefExpr(Reference r, SourcePosition posn) {
super(posn);
ref = r;
}
public RefExpr(Reference r, SourcePosition posn) {
super(posn);
ref = r;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitRefExpr(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitRefExpr(this, o);
}
public Reference ref;
public Reference ref;
}

View File

@ -9,11 +9,11 @@ import miniJava.CodeGenerator.RuntimeEntity;
import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class Reference extends AST {
public Reference(SourcePosition posn) {
super(posn);
}
public Reference(SourcePosition posn) {
super(posn);
}
public String spelling;
public Declaration decl;
public RuntimeEntity entity;
public String spelling;
public Declaration decl;
public RuntimeEntity entity;
}

View File

@ -9,8 +9,8 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public abstract class Statement extends AST {
public Statement(SourcePosition posn) {
super(posn);
}
public Statement(SourcePosition posn) {
super(posn);
}
}

View File

@ -8,25 +8,25 @@ package miniJava.AbstractSyntaxTrees;
import java.util.*;
public class StatementList implements Iterable<Statement> {
public StatementList() {
slist = new ArrayList<Statement>();
}
public StatementList() {
slist = new ArrayList<Statement>();
}
public void add(Statement s) {
slist.add(s);
}
public void add(Statement s) {
slist.add(s);
}
public Statement get(int i) {
return slist.get(i);
}
public Statement get(int i) {
return slist.get(i);
}
public int size() {
return slist.size();
}
public int size() {
return slist.size();
}
public Iterator<Statement> iterator() {
return slist.iterator();
}
public Iterator<Statement> iterator() {
return slist.iterator();
}
private List<Statement> slist;
private List<Statement> slist;
}

View File

@ -9,10 +9,10 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
abstract public class Terminal extends AST {
public Terminal(String s, SourcePosition posn) {
super(posn);
spelling = s;
}
public Terminal(String s, SourcePosition posn) {
super(posn);
spelling = s;
}
public String spelling;
public String spelling;
}

View File

@ -9,13 +9,13 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class ThisRef extends Reference {
public ThisRef(SourcePosition posn) {
super(posn);
}
public ThisRef(SourcePosition posn) {
super(posn);
}
@Override
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitThisRef(this, o);
}
@Override
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitThisRef(this, o);
}
}

View File

@ -9,11 +9,11 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
abstract public class Type extends AST {
public Type(TypeKind typ, SourcePosition posn) {
super(posn);
typeKind = typ;
}
public Type(TypeKind typ, SourcePosition posn) {
super(posn);
typeKind = typ;
}
public TypeKind typeKind;
public TypeKind typeKind;
}

View File

@ -6,5 +6,5 @@
package miniJava.AbstractSyntaxTrees;
public enum TypeKind {
VOID, INT, BOOLEAN, CLASS, ARRAY, UNSUPPORTED, ERROR;
VOID, INT, BOOLEAN, CLASS, ARRAY, UNSUPPORTED, ERROR;
}

View File

@ -8,16 +8,16 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class UnaryExpr extends Expression {
public UnaryExpr(Operator o, Expression e, SourcePosition posn) {
super(posn);
operator = o;
expr = e;
}
public UnaryExpr(Operator o, Expression e, SourcePosition posn) {
super(posn);
operator = o;
expr = e;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitUnaryExpr(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitUnaryExpr(this, o);
}
public Operator operator;
public Expression expr;
public Operator operator;
public Expression expr;
}

View File

@ -9,11 +9,11 @@ import miniJava.SyntacticAnalyzer.SourcePosition;
public class VarDecl extends LocalDecl {
public VarDecl(Type t, String name, SourcePosition posn) {
super(name, t, posn);
}
public VarDecl(Type t, String name, SourcePosition posn) {
super(name, t, posn);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitVarDecl(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitVarDecl(this, o);
}
}

View File

@ -8,16 +8,16 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class VarDeclStmt extends Statement {
public VarDeclStmt(VarDecl vd, Expression e, SourcePosition posn) {
super(posn);
varDecl = vd;
initExp = e;
}
public VarDeclStmt(VarDecl vd, Expression e, SourcePosition posn) {
super(posn);
varDecl = vd;
initExp = e;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitVardeclStmt(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitVardeclStmt(this, o);
}
public VarDecl varDecl;
public Expression initExp;
public VarDecl varDecl;
public Expression initExp;
}

View File

@ -11,70 +11,70 @@ package miniJava.AbstractSyntaxTrees;
*/
public interface Visitor<ArgType, ResultType> {
// Package
public ResultType visitPackage(Package prog, ArgType arg);
// Package
public ResultType visitPackage(Package prog, ArgType arg);
// Declarations
public ResultType visitClassDecl(ClassDecl cd, ArgType arg);
// Declarations
public ResultType visitClassDecl(ClassDecl cd, ArgType arg);
public ResultType visitFieldDecl(FieldDecl fd, ArgType arg);
public ResultType visitFieldDecl(FieldDecl fd, ArgType arg);
public ResultType visitMethodDecl(MethodDecl md, ArgType arg);
public ResultType visitMethodDecl(MethodDecl md, ArgType arg);
public ResultType visitParameterDecl(ParameterDecl pd, ArgType arg);
public ResultType visitParameterDecl(ParameterDecl pd, ArgType arg);
public ResultType visitVarDecl(VarDecl decl, ArgType arg);
public ResultType visitVarDecl(VarDecl decl, ArgType arg);
// Types
public ResultType visitBaseType(BaseType type, ArgType arg);
// Types
public ResultType visitBaseType(BaseType type, ArgType arg);
public ResultType visitClassType(ClassType type, ArgType arg);
public ResultType visitClassType(ClassType type, ArgType arg);
public ResultType visitArrayType(ArrayType type, ArgType arg);
public ResultType visitArrayType(ArrayType type, ArgType arg);
// Statements
public ResultType visitBlockStmt(BlockStmt stmt, ArgType arg);
// Statements
public ResultType visitBlockStmt(BlockStmt stmt, ArgType arg);
public ResultType visitVardeclStmt(VarDeclStmt stmt, ArgType arg);
public ResultType visitVardeclStmt(VarDeclStmt stmt, ArgType arg);
public ResultType visitAssignStmt(AssignStmt stmt, ArgType arg);
public ResultType visitAssignStmt(AssignStmt stmt, ArgType arg);
public ResultType visitCallStmt(CallStmt stmt, ArgType arg);
public ResultType visitCallStmt(CallStmt stmt, ArgType arg);
public ResultType visitIfStmt(IfStmt stmt, ArgType arg);
public ResultType visitIfStmt(IfStmt stmt, ArgType arg);
public ResultType visitWhileStmt(WhileStmt stmt, ArgType arg);
public ResultType visitWhileStmt(WhileStmt stmt, ArgType arg);
// Expressions
public ResultType visitUnaryExpr(UnaryExpr expr, ArgType arg);
// Expressions
public ResultType visitUnaryExpr(UnaryExpr expr, ArgType arg);
public ResultType visitBinaryExpr(BinaryExpr expr, ArgType arg);
public ResultType visitBinaryExpr(BinaryExpr expr, ArgType arg);
public ResultType visitRefExpr(RefExpr expr, ArgType arg);
public ResultType visitRefExpr(RefExpr expr, ArgType arg);
public ResultType visitCallExpr(CallExpr expr, ArgType arg);
public ResultType visitCallExpr(CallExpr expr, ArgType arg);
public ResultType visitLiteralExpr(LiteralExpr expr, ArgType arg);
public ResultType visitLiteralExpr(LiteralExpr expr, ArgType arg);
public ResultType visitNewObjectExpr(NewObjectExpr expr, ArgType arg);
public ResultType visitNewObjectExpr(NewObjectExpr expr, ArgType arg);
public ResultType visitNewArrayExpr(NewArrayExpr expr, ArgType arg);
public ResultType visitNewArrayExpr(NewArrayExpr expr, ArgType arg);
// References
public ResultType visitQualifiedRef(QualifiedRef ref, ArgType arg);
// References
public ResultType visitQualifiedRef(QualifiedRef ref, ArgType arg);
public ResultType visitIndexedRef(IndexedRef ref, ArgType arg);
public ResultType visitIndexedRef(IndexedRef ref, ArgType arg);
public ResultType visitIdRef(IdRef ref, ArgType arg);
public ResultType visitIdRef(IdRef ref, ArgType arg);
public ResultType visitThisRef(ThisRef ref, ArgType arg);
public ResultType visitThisRef(ThisRef ref, ArgType arg);
// Terminals
public ResultType visitIdentifier(Identifier id, ArgType arg);
// Terminals
public ResultType visitIdentifier(Identifier id, ArgType arg);
public ResultType visitOperator(Operator op, ArgType arg);
public ResultType visitOperator(Operator op, ArgType arg);
public ResultType visitIntLiteral(IntLiteral num, ArgType arg);
public ResultType visitIntLiteral(IntLiteral num, ArgType arg);
public ResultType visitBooleanLiteral(BooleanLiteral bool, ArgType arg);
public ResultType visitBooleanLiteral(BooleanLiteral bool, ArgType arg);
}

View File

@ -8,16 +8,16 @@ package miniJava.AbstractSyntaxTrees;
import miniJava.SyntacticAnalyzer.SourcePosition;
public class WhileStmt extends Statement {
public WhileStmt(Expression b, Statement s, SourcePosition posn) {
super(posn);
cond = b;
body = s;
}
public WhileStmt(Expression b, Statement s, SourcePosition posn) {
super(posn);
cond = b;
body = s;
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitWhileStmt(this, o);
}
public <A, R> R visit(Visitor<A, R> v, A o) {
return v.visitWhileStmt(this, o);
}
public Expression cond;
public Statement body;
public Expression cond;
public Statement body;
}

View File

@ -4,52 +4,53 @@ import mJAM.Machine;
import miniJava.AbstractSyntaxTrees.*;
public class Code {
public boolean addr;
public Declaration decl;
/**
* If addr true, returns the address of the declaration.
* Otherwise, uses the size of the declaration in its place.
* @param op
* @param decl
* @param addr
*/
public Code(Declaration decl, boolean addr) {
this.decl = decl;
this.addr = addr;
}
/**
*
* @param index
*/
public void modify(int instr) {
// Setup size
switch(decl.type.typeKind) {
case ARRAY:
case CLASS:
Machine.code[instr].n = Machine.addressSize;
case INT:
Machine.code[instr].n = Machine.integerSize;
case BOOLEAN:
Machine.code[instr].n = Machine.booleanSize;
case VOID:
Machine.code[instr].n = 0;
default:
Machine.code[instr].n = -1;
}
// Setup displacement
if(addr) {
Machine.code[instr].d += decl.entity.addr;
} else {
Machine.code[instr].d += decl.entity.size;
}
// Setup register
Machine.code[instr].r = decl.entity.reg.ordinal();
}
public boolean addr;
public Declaration decl;
/**
* If addr true, returns the address of the declaration. Otherwise, uses the
* size of the declaration in its place.
*
* @param op
* @param decl
* @param addr
*/
public Code(Declaration decl, boolean addr) {
this.decl = decl;
this.addr = addr;
}
/**
*
* @param index
*/
public void modify(int instr) {
// Setup size
switch (decl.type.typeKind) {
case ARRAY:
case CLASS:
Machine.code[instr].n = Machine.addressSize;
case INT:
Machine.code[instr].n = Machine.integerSize;
case BOOLEAN:
Machine.code[instr].n = Machine.booleanSize;
case VOID:
Machine.code[instr].n = 0;
default:
Machine.code[instr].n = -1;
}
// Setup displacement
if (addr) {
Machine.code[instr].d += decl.entity.addr;
} else {
Machine.code[instr].d += decl.entity.size;
}
// Setup register
Machine.code[instr].r = decl.entity.reg.ordinal();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -4,16 +4,16 @@ import mJAM.Machine.Reg;
public class RuntimeEntity {
public Reg reg;
public int size;
public int addr;
RuntimeEntity parent = null;
public RuntimeEntity(int size, int addr, Reg reg) {
this.reg = reg;
this.size = size;
this.addr = addr;
}
public Reg reg;
public int size;
public int addr;
RuntimeEntity parent = null;
public RuntimeEntity(int size, int addr, Reg reg) {
this.reg = reg;
this.size = size;
this.addr = addr;
}
}

View File

@ -19,58 +19,58 @@ import miniJava.ContextualAnalyzer.Reporter;
public class Compiler {
public static final int rc = 4;
public static final int rc = 4;
public static void main(String[] args) {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No file specified");
System.exit(rc);
}
if (args.length == 0) {
System.out.println("No file specified");
System.exit(rc);
}
try (FileReader input = new FileReader(args[0])) {
try (FileReader input = new FileReader(args[0])) {
// Setup
Scanner scanner = new Scanner(new BufferedReader(input));
Parser parser = new Parser(scanner);
Package p = parser.parse();
// Display
// ASTDisplay display = new ASTDisplay();
// display.showTree(p);
// Contextual Analyzer
IdTable table = new IdTable();
Analyzer analyzer = new Analyzer();
analyzer.visitPackage(p, table);
// Compilation
if(Reporter.error) {
System.exit(rc);
} else {
// Build mJAM assembly
Encoder encoder = new Encoder();
encoder.visitPackage(p, null);
// Create object file
int pos = args[0].lastIndexOf(".java");
String objectFileName = args[0].substring(0, pos) + ".mJAM";
ObjectFile objF = new ObjectFile(objectFileName);
if(objF.write()) {
Reporter.emit("Object File Failed.");
}
}
System.exit(0);
// Setup
Scanner scanner = new Scanner(new BufferedReader(input));
Parser parser = new Parser(scanner);
Package p = parser.parse();
} catch (FileNotFoundException e) {
Reporter.emit(e.getMessage());
} catch (IOException e) {
Reporter.emit(e.getMessage());
}
// Display
// ASTDisplay display = new ASTDisplay();
// display.showTree(p);
System.exit(rc);
}
// Contextual Analyzer
IdTable table = new IdTable();
Analyzer analyzer = new Analyzer();
analyzer.visitPackage(p, table);
// Compilation
if (Reporter.error) {
System.exit(rc);
} else {
// Build mJAM assembly
Encoder encoder = new Encoder();
encoder.visitPackage(p, null);
// Create object file
int pos = args[0].lastIndexOf(".java");
String objectFileName = args[0].substring(0, pos) + ".mJAM";
ObjectFile objF = new ObjectFile(objectFileName);
if (objF.write()) {
Reporter.emit("Object File Failed.");
}
}
System.exit(0);
} catch (FileNotFoundException e) {
Reporter.emit(e.getMessage());
} catch (IOException e) {
Reporter.emit(e.getMessage());
}
System.exit(rc);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -10,118 +10,118 @@ import miniJava.AbstractSyntaxTrees.*;
*
*/
public class IdTable {
private IdTable parent;
private ArrayList<HashMap<String, Declaration>> scope;
// /////////////////////////////////////////////////////////////////////////////
//
// CONSTRUCTORS
//
// /////////////////////////////////////////////////////////////////////////////
/**
*
*/
public IdTable() {
this(null);
}
/**
*
* @param parent
*/
public IdTable(IdTable parent) {
this.parent = parent;
this.scope = new ArrayList<>();
push();
}
// /////////////////////////////////////////////////////////////////////////////
//
// ACTIVE SCOPE
//
// /////////////////////////////////////////////////////////////////////////////
private IdTable parent;
private ArrayList<HashMap<String, Declaration>> scope;
/**
*
*/
public void pop() {
int last = scope.size() - 1;
scope.remove(last);
}
/**
*
*/
public void push() {
HashMap<String, Declaration> nested = new HashMap<>();
scope.add(nested);
}
/**
*
*/
public void add(Declaration decl) {
for(int i = 0; i < scope.size(); i++) {
HashMap<String, Declaration> nest = scope.get(i);
if(nest.containsKey(decl.name)) {
Declaration prev = nest.get(decl.name);
if(decl instanceof ClassDecl) {
Reporter.report(decl, prev, "Class");
} else if(decl instanceof FieldDecl) {
Reporter.report(decl, prev, "Field");
} else if(decl instanceof MethodDecl) {
Reporter.report(decl, prev, "Method");
} else if(decl instanceof ParameterDecl) {
Reporter.report(decl, prev, "Parameter");
} else if(decl instanceof VarDecl) {
Reporter.report(decl, prev, "Variable");
}
System.exit(Compiler.rc);
}
}
scope.get(scope.size()-1).put(decl.name, decl);
}
// /////////////////////////////////////////////////////////////////////////////
//
// GETTERS
//
// /////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////
//
// CONSTRUCTORS
//
// /////////////////////////////////////////////////////////////////////////////
/**
*
* @param name
*/
public Declaration getDeclaration(String name) {
IdTable current = this;
while (current != null) {
Declaration decl = current.getDeclarationAtScope(name);
if (decl == null) current = current.parent;
else return decl;
}
/**
*
*/
public IdTable() {
this(null);
}
return null;
}
/**
*
* @param name
*/
public Declaration getDeclarationAtScope(String name) {
for (int i = scope.size() - 1; i >= 0; i--) {
HashMap<String, Declaration> nest = scope.get(i);
if (nest.containsKey(name)) return nest.get(name);
}
return null;
}
/**
*
* @param parent
*/
public IdTable(IdTable parent) {
this.parent = parent;
this.scope = new ArrayList<>();
push();
}
// /////////////////////////////////////////////////////////////////////////////
//
// ACTIVE SCOPE
//
// /////////////////////////////////////////////////////////////////////////////
/**
*
*/
public void pop() {
int last = scope.size() - 1;
scope.remove(last);
}
/**
*
*/
public void push() {
HashMap<String, Declaration> nested = new HashMap<>();
scope.add(nested);
}
/**
*
*/
public void add(Declaration decl) {
for (int i = 0; i < scope.size(); i++) {
HashMap<String, Declaration> nest = scope.get(i);
if (nest.containsKey(decl.name)) {
Declaration prev = nest.get(decl.name);
if (decl instanceof ClassDecl) {
Reporter.report(decl, prev, "Class");
} else if (decl instanceof FieldDecl) {
Reporter.report(decl, prev, "Field");
} else if (decl instanceof MethodDecl) {
Reporter.report(decl, prev, "Method");
} else if (decl instanceof ParameterDecl) {
Reporter.report(decl, prev, "Parameter");
} else if (decl instanceof VarDecl) {
Reporter.report(decl, prev, "Variable");
}
System.exit(Compiler.rc);
}
}
scope.get(scope.size() - 1).put(decl.name, decl);
}
// /////////////////////////////////////////////////////////////////////////////
//
// GETTERS
//
// /////////////////////////////////////////////////////////////////////////////
/**
*
* @param name
*/
public Declaration getDeclaration(String name) {
IdTable current = this;
while (current != null) {
Declaration decl = current.getDeclarationAtScope(name);
if (decl == null)
current = current.parent;
else
return decl;
}
return null;
}
/**
*
* @param name
*/
public Declaration getDeclarationAtScope(String name) {
for (int i = scope.size() - 1; i >= 0; i--) {
HashMap<String, Declaration> nest = scope.get(i);
if (nest.containsKey(name))
return nest.get(name);
}
return null;
}
}

View File

@ -3,25 +3,26 @@ package miniJava.ContextualAnalyzer;
import miniJava.AbstractSyntaxTrees.Declaration;
public class Reporter {
public static boolean error = false;
/**
*
* @param message
*/
public static void emit(String message) {
error = true;
System.out.println("***" + message);
}
/**
* Redefinitions
* @param d1
* @param d2
*/
public static void report(Declaration d1, Declaration d2, String prefix) {
emit(prefix + " at " + d1.posn + " previously defined at " + d2.posn);
}
public static boolean error = false;
/**
*
* @param message
*/
public static void emit(String message) {
error = true;
System.out.println("***" + message);
}
/**
* Redefinitions
*
* @param d1
* @param d2
*/
public static void report(Declaration d1, Declaration d2, String prefix) {
emit(prefix + " at " + d1.posn + " previously defined at " + d2.posn);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -6,11 +6,11 @@ import java.io.IOException;
*
*/
public class ParsingException extends IOException {
private static final long serialVersionUID = 1L;
public ParsingException(SourcePosition posn) {
super("Parsing error at " + posn);
}
private static final long serialVersionUID = 1L;
public ParsingException(SourcePosition posn) {
super("Parsing error at " + posn);
}
}

View File

@ -4,303 +4,300 @@ import java.io.*;
public class Scanner {
private int col = 1;
private int line = 1;
private boolean predefined;
private BufferedReader input;
/**
*
* @param input
*/
public Scanner(BufferedReader input) {
this(input, false);
}
/**
*
* @param input
* @param predefined
*/
public Scanner(String input, boolean predefined) {
this(new BufferedReader(new StringReader(input)), predefined);
}
/**
*
* @param input
* @param predefined
*/
public Scanner(BufferedReader input, boolean predefined) {
this.input = input;
this.predefined = predefined;
}
private int col = 1;
private int line = 1;
private boolean predefined;
private BufferedReader input;
// /////////////////////////////////////////////////////////////////////////////
//
// Scanning
//
// /////////////////////////////////////////////////////////////////////////////
/**
*
* @return
* @throws IOException
*/
public Token scan() throws IOException {
Token token = null;
String spelling = "";
while (token == null) {
int c = read();
SourcePosition posn = new SourcePosition(col, line);
if(c == -1) {
token = new Token("", Token.TYPE.EOT, posn);
} else {
spelling += (char) c;
switch(c) {
/**
*
* @param input
*/
public Scanner(BufferedReader input) {
this(input, false);
}
// Operators
case '*':
case '+':
case '-': {
if(peek(c)) throw new ScanningException(posn);
token = new Token(spelling, Token.TYPE.BINOP, posn);
break;
}
// Comment
case '/': {
if(peek('*')) {
read();
readMultiLineComment();
spelling = "";
} else if(peek('/')) {
readSingleLineComment();
spelling = "";
} else {
token = new Token(spelling, Token.TYPE.BINOP, posn);
}
break;
}
// Relational
case '>':
case '<': {
if (peek('=')) spelling += (char) read();
token = new Token(spelling, Token.TYPE.BINOP, posn);
break;
}
// Negation
case '!': {
if(peek('=')) {
spelling += (char) read();
token = new Token(spelling, Token.TYPE.BINOP, posn);
} else {
token = new Token(spelling, Token.TYPE.UNOP, posn);
}
break;
}
// Logical
case '&':
case '|': {
if(!peek(c)) {
throw new ScanningException(posn);
} else {
spelling += (char) read();
token = new Token(spelling, Token.TYPE.BINOP, posn);
}
break;
}
// Other Operators
case '=': {
if(peek('=')) {
spelling += (char) read();
token = new Token(spelling, Token.TYPE.BINOP, posn);
} else {
token = new Token(spelling, Token.TYPE.EQUALS, posn);
}
break;
}
// Miscellaneous
case '.':
case ',':
case '[':
case ']':
case '{':
case '}':
case '(':
case ')':
case ';': {
token = new Token(spelling, Token.symbols.get(c), posn);
break;
}
default: {
// Identifier or keyword
if(isAlpha(c)) {
int next = peek();
while(isAlpha(next) || isDigit(next) || next == '_') {
spelling += (char) read();
next = peek();
}
if(Token.keywords.containsKey(spelling)) {
token = new Token(spelling, Token.keywords.get(spelling), posn);
} else {
token = new Token(spelling, Token.TYPE.ID, posn);
}
}
// Number
else if(isDigit(c)) {
int next = peek();
while(isDigit(next)) {
spelling += (char) read();
next = peek();
}
/**
*
* @param input
* @param predefined
*/
public Scanner(String input, boolean predefined) {
this(new BufferedReader(new StringReader(input)), predefined);
}
token = new Token(spelling, Token.TYPE.NUM, posn);
}
// Whitespace
else if(isWhitespace(c)) {
spelling = "";
}
// Unrecognized Character
else {
throw new ScanningException(posn);
}
}
}
}
}
/**
*
* @param input
* @param predefined
*/
public Scanner(BufferedReader input, boolean predefined) {
this.input = input;
this.predefined = predefined;
}
return token;
}
// /////////////////////////////////////////////////////////////////////////////
//
// Scanning
//
// /////////////////////////////////////////////////////////////////////////////
/**
*
* @return
* @throws IOException
*/
public Token scan() throws IOException {
Token token = null;
String spelling = "";
// /////////////////////////////////////////////////////////////////////////////
//
// Convenience Methods
//
// /////////////////////////////////////////////////////////////////////////////
/**
*
* @param c
* @return
*/
private boolean isAlpha(int c) {
return (c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (predefined && c == '_');
}
/**
*
* @param c
* @return
*/
private boolean isDigit(int c) {
return c >= '0' && c <= '9';
}
/**
*
* @param c
* @return
*/
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t';
}
/**
*
* @return
* @throws IOException
*/
private int peek() throws IOException {
input.mark(1);
int next = input.read();
input.reset();
while (token == null) {
return next;
}
/**
*
* @param c
* @return
* @throws IOException
*/
private boolean peek(int c) throws IOException {
input.mark(1);
int next = input.read();
input.reset();
int c = read();
SourcePosition posn = new SourcePosition(col, line);
return c == next;
}
/**
*
* @return
* @throws IOException
*/
private int read() throws IOException {
int next = input.read();
if(next == '\n' || next == '\r') {
col = 1;
line += 1;
} else {
col += 1;
}
return next;
}
/**
*
* @throws IOException
*/
private void readSingleLineComment() throws IOException {
col = 1;
line += 1;
input.readLine();
}
if (c == -1) {
token = new Token("", Token.TYPE.EOT, posn);
} else {
spelling += (char) c;
/**
*
* @throws IOException
*/
private void readMultiLineComment() throws IOException {
int prev = '\0';
int current = '\0';
while(prev != '*' || current != '/') {
prev = current;
current = read();
// Unterminated
if(current == -1) {
SourcePosition posn = new SourcePosition(line, col);
throw new ScanningException(posn);
}
}
}
switch (c) {
// Operators
case '*':
case '+':
case '-': {
if (peek(c))
throw new ScanningException(posn);
token = new Token(spelling, Token.TYPE.BINOP, posn);
break;
}
// Comment
case '/': {
if (peek('*')) {
read();
readMultiLineComment();
spelling = "";
} else if (peek('/')) {
readSingleLineComment();
spelling = "";
} else {
token = new Token(spelling, Token.TYPE.BINOP, posn);
}
break;
}
// Relational
case '>':
case '<': {
if (peek('='))
spelling += (char) read();
token = new Token(spelling, Token.TYPE.BINOP, posn);
break;
}
// Negation
case '!': {
if (peek('=')) {
spelling += (char) read();
token = new Token(spelling, Token.TYPE.BINOP, posn);
} else {
token = new Token(spelling, Token.TYPE.UNOP, posn);
}
break;
}
// Logical
case '&':
case '|': {
if (!peek(c)) {
throw new ScanningException(posn);
} else {
spelling += (char) read();
token = new Token(spelling, Token.TYPE.BINOP, posn);
}
break;
}
// Other Operators
case '=': {
if (peek('=')) {
spelling += (char) read();
token = new Token(spelling, Token.TYPE.BINOP, posn);
} else {
token = new Token(spelling, Token.TYPE.EQUALS, posn);
}
break;
}
// Miscellaneous
case '.':
case ',':
case '[':
case ']':
case '{':
case '}':
case '(':
case ')':
case ';': {
token = new Token(spelling, Token.symbols.get(c), posn);
break;
}
default: {
// Identifier or keyword
if (isAlpha(c)) {
int next = peek();
while (isAlpha(next) || isDigit(next) || next == '_') {
spelling += (char) read();
next = peek();
}
if (Token.keywords.containsKey(spelling)) {
token = new Token(spelling, Token.keywords.get(spelling), posn);
} else {
token = new Token(spelling, Token.TYPE.ID, posn);
}
}
// Number
else if (isDigit(c)) {
int next = peek();
while (isDigit(next)) {
spelling += (char) read();
next = peek();
}
token = new Token(spelling, Token.TYPE.NUM, posn);
}
// Whitespace
else if (isWhitespace(c)) {
spelling = "";
}
// Unrecognized Character
else {
throw new ScanningException(posn);
}
}
}
}
}
return token;
}
// /////////////////////////////////////////////////////////////////////////////
//
// Convenience Methods
//
// /////////////////////////////////////////////////////////////////////////////
/**
*
* @param c
* @return
*/
private boolean isAlpha(int c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (predefined && c == '_');
}
/**
*
* @param c
* @return
*/
private boolean isDigit(int c) {
return c >= '0' && c <= '9';
}
/**
*
* @param c
* @return
*/
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t';
}
/**
*
* @return
* @throws IOException
*/
private int peek() throws IOException {
input.mark(1);
int next = input.read();
input.reset();
return next;
}
/**
*
* @param c
* @return
* @throws IOException
*/
private boolean peek(int c) throws IOException {
input.mark(1);
int next = input.read();
input.reset();
return c == next;
}
/**
*
* @return
* @throws IOException
*/
private int read() throws IOException {
int next = input.read();
if (next == '\n' || next == '\r') {
col = 1;
line += 1;
} else {
col += 1;
}
return next;
}
/**
*
* @throws IOException
*/
private void readSingleLineComment() throws IOException {
col = 1;
line += 1;
input.readLine();
}
/**
*
* @throws IOException
*/
private void readMultiLineComment() throws IOException {
int prev = '\0';
int current = '\0';
while (prev != '*' || current != '/') {
prev = current;
current = read();
// Unterminated
if (current == -1) {
SourcePosition posn = new SourcePosition(line, col);
throw new ScanningException(posn);
}
}
}
}

View File

@ -6,11 +6,11 @@ import java.io.IOException;
*
*/
public class ScanningException extends IOException {
private static final long serialVersionUID = 1L;
public ScanningException(SourcePosition posn) {
super("Scanning error at " + posn);
}
private static final long serialVersionUID = 1L;
public ScanningException(SourcePosition posn) {
super("Scanning error at " + posn);
}
}

View File

@ -5,16 +5,16 @@ package miniJava.SyntacticAnalyzer;
*/
public class SourcePosition {
public final int col;
public final int line;
public final int col;
public final int line;
public SourcePosition(int col, int line) {
this.col = col;
this.line = line;
}
public SourcePosition(int col, int line) {
this.col = col;
this.line = line;
}
@Override
public String toString() {
return "(Line: " + line + ", Column: " + col + ")";
}
@Override
public String toString() {
return "(Line: " + line + ", Column: " + col + ")";
}
}

View File

@ -7,88 +7,63 @@ import java.util.HashMap;
*/
public class Token {
public enum TYPE {
// Terminals
ID,
NUM,
UNOP,
BINOP,
EQUALS,
PERIOD,
COMMA,
LPAREN,
RPAREN,
LSQUARE,
RSQUARE,
LBRACKET,
RBRACKET,
SEMICOLON,
public enum TYPE {
// Keywords
IF,
ELSE,
NEW,
INT,
VOID,
THIS,
TRUE,
FALSE,
CLASS,
WHILE,
RETURN,
BOOLEAN,
STATIC,
PUBLIC,
PRIVATE,
// Terminals
ID, NUM, UNOP, BINOP, EQUALS, PERIOD, COMMA, LPAREN, RPAREN, LSQUARE, RSQUARE, LBRACKET, RBRACKET, SEMICOLON,
// End of Token Stream
EOT
};
// Keywords
IF, ELSE, NEW, INT, VOID, THIS, TRUE, FALSE, CLASS, WHILE, RETURN, BOOLEAN, STATIC, PUBLIC, PRIVATE,
// Pair words with enumeration
public final static HashMap<String, TYPE> keywords;
static {
keywords = new HashMap<String, TYPE>();
keywords.put("class", TYPE.CLASS);
keywords.put("return", TYPE.RETURN);
keywords.put("public", TYPE.PUBLIC);
keywords.put("private", TYPE.PRIVATE);
keywords.put("static", TYPE.STATIC);
keywords.put("int", TYPE.INT);
keywords.put("boolean", TYPE.BOOLEAN);
keywords.put("void", TYPE.VOID);
keywords.put("this", TYPE.THIS);
keywords.put("if", TYPE.IF);
keywords.put("else", TYPE.ELSE);
keywords.put("while", TYPE.WHILE);
keywords.put("true", TYPE.TRUE);
keywords.put("false", TYPE.FALSE);
keywords.put("new", TYPE.NEW);
}
// Pair symbols with enumeration
public final static HashMap<Integer, TYPE> symbols;
static {
symbols = new HashMap<Integer, TYPE>();
symbols.put((int) '.', TYPE.PERIOD);
symbols.put((int) ',', TYPE.COMMA);
symbols.put((int) '[', TYPE.LSQUARE);
symbols.put((int) ']', TYPE.RSQUARE);
symbols.put((int) '{', TYPE.LBRACKET);
symbols.put((int) '}', TYPE.RBRACKET);
symbols.put((int) '(', TYPE.LPAREN);
symbols.put((int) ')', TYPE.RPAREN);
symbols.put((int) ';', TYPE.SEMICOLON);
}
// End of Token Stream
EOT
};
public final TYPE type;
public final String spelling;
public final SourcePosition posn;
// Pair words with enumeration
public final static HashMap<String, TYPE> keywords;
public Token(String spelling, TYPE type, SourcePosition posn) {
this.type = type;
this.posn = posn;
this.spelling = spelling;
}
static {
keywords = new HashMap<String, TYPE>();
keywords.put("class", TYPE.CLASS);
keywords.put("return", TYPE.RETURN);
keywords.put("public", TYPE.PUBLIC);
keywords.put("private", TYPE.PRIVATE);
keywords.put("static", TYPE.STATIC);
keywords.put("int", TYPE.INT);
keywords.put("boolean", TYPE.BOOLEAN);
keywords.put("void", TYPE.VOID);
keywords.put("this", TYPE.THIS);
keywords.put("if", TYPE.IF);
keywords.put("else", TYPE.ELSE);
keywords.put("while", TYPE.WHILE);
keywords.put("true", TYPE.TRUE);
keywords.put("false", TYPE.FALSE);
keywords.put("new", TYPE.NEW);
}
// Pair symbols with enumeration
public final static HashMap<Integer, TYPE> symbols;
static {
symbols = new HashMap<Integer, TYPE>();
symbols.put((int) '.', TYPE.PERIOD);
symbols.put((int) ',', TYPE.COMMA);
symbols.put((int) '[', TYPE.LSQUARE);
symbols.put((int) ']', TYPE.RSQUARE);
symbols.put((int) '{', TYPE.LBRACKET);
symbols.put((int) '}', TYPE.RBRACKET);
symbols.put((int) '(', TYPE.LPAREN);
symbols.put((int) ')', TYPE.RPAREN);
symbols.put((int) ';', TYPE.SEMICOLON);
}
public final TYPE type;
public final String spelling;
public final SourcePosition posn;
public Token(String spelling, TYPE type, SourcePosition posn) {
this.type = type;
this.posn = posn;
this.spelling = spelling;
}
}

View File

@ -12,60 +12,59 @@ import java.util.concurrent.Executors;
* Put your tests in "tests/pa1_tests" folder in your Eclipse workspace directory
*/
public class Checkpoint1 {
static ExecutorService threadPool = Executors.newCachedThreadPool();
public static void main(String[] args) throws IOException, InterruptedException {
File testDir = new File(System.getProperty("java.class.path")
+ "/../tests/pa1_tests");
int failures = 0;
for (File x : testDir.listFiles()) {
int returnCode = runTest(x);
if (x.getName().indexOf("pass") != -1) {
if (returnCode == 0)
System.out.println(x.getName() + " passed successfully!");
else {
failures++;
System.err.println(x.getName()
+ " failed but should have passed!");
}
} else {
if (returnCode == 4)
System.out.println(x.getName() + " failed successfully!");
else {
System.err.println(x.getName() + " did not fail properly!");
failures++;
}
}
}
System.out.println(failures + " failures in all.");
}
private static int runTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "miniJava.Compiler", x.getPath()).directory(new File(System.getProperty("java.class.path")));
Process p = pb.start();
threadPool.execute(new ProcessOutputter(p.getInputStream(), false));
p.waitFor();
return p.exitValue();
}
static class ProcessOutputter implements Runnable {
private Scanner processOutput;
private boolean output;
public ProcessOutputter(InputStream _processStream, boolean _output) {
processOutput = new Scanner(_processStream);
output = _output;
}
@Override
public void run() {
while(processOutput.hasNextLine()) {
String line = processOutput.nextLine();
if (output)
System.out.println(line);
}
}
}
static ExecutorService threadPool = Executors.newCachedThreadPool();
public static void main(String[] args) throws IOException, InterruptedException {
File testDir = new File(System.getProperty("java.class.path") + "/../tests/pa1_tests");
int failures = 0;
for (File x : testDir.listFiles()) {
int returnCode = runTest(x);
if (x.getName().indexOf("pass") != -1) {
if (returnCode == 0)
System.out.println(x.getName() + " passed successfully!");
else {
failures++;
System.err.println(x.getName() + " failed but should have passed!");
}
} else {
if (returnCode == 4)
System.out.println(x.getName() + " failed successfully!");
else {
System.err.println(x.getName() + " did not fail properly!");
failures++;
}
}
}
System.out.println(failures + " failures in all.");
}
private static int runTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "miniJava.Compiler", x.getPath())
.directory(new File(System.getProperty("java.class.path")));
Process p = pb.start();
threadPool.execute(new ProcessOutputter(p.getInputStream(), false));
p.waitFor();
return p.exitValue();
}
static class ProcessOutputter implements Runnable {
private Scanner processOutput;
private boolean output;
public ProcessOutputter(InputStream _processStream, boolean _output) {
processOutput = new Scanner(_processStream);
output = _output;
}
@Override
public void run() {
while (processOutput.hasNextLine()) {
String line = processOutput.nextLine();
if (output)
System.out.println(line);
}
}
}
}

View File

@ -13,86 +13,84 @@ import java.util.Scanner;
*/
public class Checkpoint2 {
private static class ReturnInfo {
int returnCode;
String ast;
public ReturnInfo(int _returnCode, String _ast) {
returnCode = _returnCode;
ast = _ast;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
File testDir = new File(System.getProperty("java.class.path")
+ "/../tests/pa2_tests");
int failures = 0;
for (File x : testDir.listFiles()) {
if (x.getName().endsWith("out") || x.getName().startsWith("."))
continue;
ReturnInfo info = runTest(x);
int returnCode = info.returnCode;
String ast = info.ast;
if (x.getName().indexOf("pass") != -1) {
if (returnCode == 0) {
String actualAST = getAST(new FileInputStream(x.getPath() + ".out"));
if (actualAST.equals(ast))
System.out.println(x.getName() + " parsed successfully and has a correct AST!");
else {
System.err.println(x.getName() + " parsed successfully but has an incorrect AST!");
failures++;
}
}
else {
failures++;
System.err.println(x.getName()
+ " failed to be parsed!");
}
} else {
if (returnCode == 4)
System.out.println(x.getName() + " failed successfully!");
else {
System.err.println(x.getName() + " did not fail properly!");
failures++;
}
}
}
System.out.println(failures + " failures in all.");
}
private static ReturnInfo runTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "miniJava.Compiler", x.getPath()).directory(new File(System.getProperty("java.class.path")));
pb.redirectErrorStream(true);
Process p = pb.start();
String ast = getAST(p.getInputStream());
p.waitFor();
int exitValue = p.exitValue();
return new ReturnInfo(exitValue, ast);
}
public static String getAST(InputStream stream) {
Scanner scan = new Scanner(stream);
String ast = null;
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.equals("======= AST Display =========================")) {
line = scan.nextLine();
while(scan.hasNext() && !line.equals("=============================================")) {
ast += line + "\n";
line = scan.nextLine();
}
}
if (line.startsWith("*** "))
System.out.println(line);
if (line.startsWith("ERROR")) {
System.out.println(line);
while(scan.hasNext())
System.out.println(scan.next());
}
}
scan.close();
return ast;
}
private static class ReturnInfo {
int returnCode;
String ast;
public ReturnInfo(int _returnCode, String _ast) {
returnCode = _returnCode;
ast = _ast;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
File testDir = new File(System.getProperty("java.class.path") + "/../tests/pa2_tests");
int failures = 0;
for (File x : testDir.listFiles()) {
if (x.getName().endsWith("out") || x.getName().startsWith("."))
continue;
ReturnInfo info = runTest(x);
int returnCode = info.returnCode;
String ast = info.ast;
if (x.getName().indexOf("pass") != -1) {
if (returnCode == 0) {
String actualAST = getAST(new FileInputStream(x.getPath() + ".out"));
if (actualAST.equals(ast))
System.out.println(x.getName() + " parsed successfully and has a correct AST!");
else {
System.err.println(x.getName() + " parsed successfully but has an incorrect AST!");
failures++;
}
} else {
failures++;
System.err.println(x.getName() + " failed to be parsed!");
}
} else {
if (returnCode == 4)
System.out.println(x.getName() + " failed successfully!");
else {
System.err.println(x.getName() + " did not fail properly!");
failures++;
}
}
}
System.out.println(failures + " failures in all.");
}
private static ReturnInfo runTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "miniJava.Compiler", x.getPath())
.directory(new File(System.getProperty("java.class.path")));
pb.redirectErrorStream(true);
Process p = pb.start();
String ast = getAST(p.getInputStream());
p.waitFor();
int exitValue = p.exitValue();
return new ReturnInfo(exitValue, ast);
}
public static String getAST(InputStream stream) {
Scanner scan = new Scanner(stream);
String ast = null;
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.equals("======= AST Display =========================")) {
line = scan.nextLine();
while (scan.hasNext() && !line.equals("=============================================")) {
ast += line + "\n";
line = scan.nextLine();
}
}
if (line.startsWith("*** "))
System.out.println(line);
if (line.startsWith("ERROR")) {
System.out.println(line);
while (scan.hasNext())
System.out.println(scan.next());
}
}
scan.close();
return ast;
}
}

View File

@ -5,7 +5,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
/* Automated regression tester for Checkpoint 3 tests
* Created by Max Beckman-Harned
* Put your tests in "tests/pa3_tests" folder in your Eclipse workspace directory
@ -13,61 +12,58 @@ import java.util.Scanner;
*/
public class Checkpoint3 {
public static void main(String[] args) throws IOException, InterruptedException {
File testDir = new File(System.getProperty("java.class.path")
+ "/../tests/pa3_tests");
int failures = 0;
for (File x : testDir.listFiles()) {
if (x.getName().endsWith("out") || x.getName().startsWith(".") || x.getName().endsWith("mJAM") || x.getName().endsWith("asm"))
continue;
int returnCode = runTest(x);
if (x.getName().indexOf("pass") != -1) {
if (returnCode == 0) {
System.out.println(x.getName() + " processed successfully!");
}
else {
failures++;
System.err.println(x.getName()
+ " failed to be processed!");
}
} else {
if (returnCode == 4)
System.out.println(x.getName() + " failed successfully!");
else {
System.err.println(x.getName() + " did not fail properly!");
failures++;
}
}
}
System.out.println(failures + " failures in all.");
}
private static int runTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "miniJava.Compiler", x.getPath()).directory(new File(System.getProperty("java.class.path")));
pb.redirectErrorStream(true);
Process p = pb.start();
processStream(p.getInputStream());
p.waitFor();
int exitValue = p.exitValue();
return exitValue;
}
public static void processStream(InputStream stream) {
Scanner scan = new Scanner(stream);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith("*** "))
System.out.println(line);
if (line.startsWith("ERROR")) {
System.out.println(line);
//while(scan.hasNext())
//System.out.println(scan.next());
}
}
scan.close();
}
public static void main(String[] args) throws IOException, InterruptedException {
File testDir = new File(System.getProperty("java.class.path") + "/../tests/pa3_tests");
int failures = 0;
for (File x : testDir.listFiles()) {
if (x.getName().endsWith("out") || x.getName().startsWith(".") || x.getName().endsWith("mJAM")
|| x.getName().endsWith("asm"))
continue;
int returnCode = runTest(x);
if (x.getName().indexOf("pass") != -1) {
if (returnCode == 0) {
System.out.println(x.getName() + " processed successfully!");
} else {
failures++;
System.err.println(x.getName() + " failed to be processed!");
}
} else {
if (returnCode == 4)
System.out.println(x.getName() + " failed successfully!");
else {
System.err.println(x.getName() + " did not fail properly!");
failures++;
}
}
}
System.out.println(failures + " failures in all.");
}
private static int runTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "miniJava.Compiler", x.getPath())
.directory(new File(System.getProperty("java.class.path")));
pb.redirectErrorStream(true);
Process p = pb.start();
processStream(p.getInputStream());
p.waitFor();
int exitValue = p.exitValue();
return exitValue;
}
public static void processStream(InputStream stream) {
Scanner scan = new Scanner(stream);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith("*** "))
System.out.println(line);
if (line.startsWith("ERROR")) {
System.out.println(line);
// while(scan.hasNext())
// System.out.println(scan.next());
}
}
scan.close();
}
}

View File

@ -5,7 +5,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
/* Automated regression tester for Checkpoint 4 tests
* Created by Max Beckman-Harned
* Put your tests in "tests/pa4_tests" folder in your Eclipse workspace directory
@ -13,100 +12,97 @@ import java.util.Scanner;
*/
public class Checkpoint4 {
public static void main(String[] args) throws IOException, InterruptedException {
File testDir = new File(System.getProperty("java.class.path")
+ "/../tests/pa4_tests");
int failures = 0;
for (File x : testDir.listFiles()) {
if (x.getName().startsWith(".") || x.getName().endsWith("mJAM") || x.getName().endsWith("asm"))
continue;
int returnCode = runTest(x);
if (x.getName().indexOf("pass") != -1) {
if (returnCode == 0) {
try {
int val = executeTest(x);
int expected = Integer.parseInt(x.getName().substring(5,7));
if (val == expected)
System.out.println(x.getName() + " ran successfully!");
else {
failures++;
System.err.println(x.getName() + " compiled but did not run successfully--got output " + val);
}
}
catch(Exception ex) {
failures++;
System.err.println(x.getName() + " did not output correctly.");
}
}
else {
failures++;
System.err.println(x.getName()
+ " failed to be processed!");
}
} else {
if (returnCode == 4)
System.out.println(x.getName() + " failed successfully!");
else {
System.err.println(x.getName() + " did not fail properly!");
failures++;
}
}
}
System.out.println(failures + " failures in all.");
}
private static int runTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "miniJava.Compiler", x.getPath()).directory(new File(System.getProperty("java.class.path")));
pb.redirectErrorStream(true);
Process p = pb.start();
processStream(p.getInputStream());
p.waitFor();
int exitValue = p.exitValue();
return exitValue;
}
private static int executeTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "mJAM.Interpreter", x.getPath().replace(".java", ".mJAM")).directory(new File(System.getProperty("java.class.path")));
Process process = pb.start();
Scanner scan = new Scanner(process.getInputStream());
int num = -1;
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith(">>> ")) {
num = Integer.parseInt(line.substring(4));
System.out.println("Result = " + num);
break;
}
}
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith("*** ")) {
System.out.println(line);
break;
}
}
scan.close();
return num;
}
public static void processStream(InputStream stream) {
Scanner scan = new Scanner(stream);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith("*** "))
System.out.println(line);
if (line.startsWith("ERROR")) {
System.out.println(line);
//while(scan.hasNext())
//System.out.println(scan.next());
}
}
scan.close();
}
public static void main(String[] args) throws IOException, InterruptedException {
File testDir = new File(System.getProperty("java.class.path") + "/../tests/pa4_tests");
int failures = 0;
for (File x : testDir.listFiles()) {
if (x.getName().startsWith(".") || x.getName().endsWith("mJAM") || x.getName().endsWith("asm"))
continue;
int returnCode = runTest(x);
if (x.getName().indexOf("pass") != -1) {
if (returnCode == 0) {
try {
int val = executeTest(x);
int expected = Integer.parseInt(x.getName().substring(5, 7));
if (val == expected)
System.out.println(x.getName() + " ran successfully!");
else {
failures++;
System.err
.println(x.getName() + " compiled but did not run successfully--got output " + val);
}
} catch (Exception ex) {
failures++;
System.err.println(x.getName() + " did not output correctly.");
}
} else {
failures++;
System.err.println(x.getName() + " failed to be processed!");
}
} else {
if (returnCode == 4)
System.out.println(x.getName() + " failed successfully!");
else {
System.err.println(x.getName() + " did not fail properly!");
failures++;
}
}
}
System.out.println(failures + " failures in all.");
}
private static int runTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "miniJava.Compiler", x.getPath())
.directory(new File(System.getProperty("java.class.path")));
pb.redirectErrorStream(true);
Process p = pb.start();
processStream(p.getInputStream());
p.waitFor();
int exitValue = p.exitValue();
return exitValue;
}
private static int executeTest(File x) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "mJAM.Interpreter", x.getPath().replace(".java", ".mJAM"))
.directory(new File(System.getProperty("java.class.path")));
Process process = pb.start();
Scanner scan = new Scanner(process.getInputStream());
int num = -1;
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith(">>> ")) {
num = Integer.parseInt(line.substring(4));
System.out.println("Result = " + num);
break;
}
}
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith("*** ")) {
System.out.println(line);
break;
}
}
scan.close();
return num;
}
public static void processStream(InputStream stream) {
Scanner scan = new Scanner(stream);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.startsWith("*** "))
System.out.println(line);
if (line.startsWith("ERROR")) {
System.out.println(line);
// while(scan.hasNext())
// System.out.println(scan.next());
}
}
scan.close();
}
}