Skip to content

Instantly share code, notes, and snippets.

@MelulekiDube
Created September 20, 2019 15:19
Show Gist options
  • Save MelulekiDube/b53991a520ae6a53b4767eff1f5564a0 to your computer and use it in GitHub Desktop.
Save MelulekiDube/b53991a520ae6a53b4767eff1f5564a0 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.io.File;
import java.io.IOException;
public class Main{
private Stack<Map<String, String>> stackTrace; // we are going to use this to store our maps
private Scanner sc; // scanner that we will use to read through the file
private StringBuilder output;
Main(String filename){
stackTrace = new Stack<>();
output = new StringBuilder();
sc = null;
try{
sc = new Scanner(new File(filename));
}catch(IOException ex){
System.out.println(ex.toString());
}
}
/**
* Method will read the next instruction and return us the instruction from the file
**/
public String getNextInstruction(){
if(sc == null){
System.out.println("Scanner is null");
return null;
}
if(sc.hasNext())
return sc.nextLine();
else{
return null;
}
}
/**
* Method to parse the instruction read and perform the action
*/
public void execute(String instruction){
String [] tokens = instruction.split(" ");
String instructionType = tokens[0]; // this gives us which instruction we are performing
output.append(instruction);
switch(instructionType){
case "define":{
String var_name = tokens[1];
String value = tokens[2];
insertToStackTrace(var_name, value);
output.append("\n");
break;
}case "use":{
String var_name = tokens[1];
String value = latestStackTraceHasName(var_name);
if(value == null)
value = "undefined";
output.append(" = ").append(value).append("\n");
break;
}case "beginscope":{
createScope();
output.append("\n");
break;
}case "endscope":{
endScope();
output.append("\n");
break;
}
}
}
public String latestStackTraceHasName(String var_name){
if(stackTrace.isEmpty())
return null;
return stackTrace.peek().getOrDefault(var_name, null);
}
public void insertToStackTrace(String var_name, String value){
if(stackTrace.isEmpty()){
//we need to create a new global Symbol table
stackTrace.push(new HashMap<>()); // we just put an empty map
}else{
}
Map<String, String> map = stackTrace.peek(); // get the lates symbol table and use that
map.put(var_name, value);
}
public void createScope(){
Map<String, String> map;
if(!stackTrace.isEmpty())
map = new HashMap<>(stackTrace.peek());
else
map = new HashMap<>();
stackTrace.push(map);
}
public void endScope(){
stackTrace.pop();
}
public static void main (String [] args){
Main main;
if(args.length > 0){
main = new Main(args[0]);
String instruction = main.getNextInstruction();
while(instruction != null){
main.execute(instruction);
instruction = main.getNextInstruction();
}
System.out.println(main.output.toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment