Skip to content

Instantly share code, notes, and snippets.

@RafayAK
Created April 29, 2016 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RafayAK/737f7f0464ada6acf9a1bf4141fcc8fb to your computer and use it in GitHub Desktop.
Save RafayAK/737f7f0464ada6acf9a1bf4141fcc8fb to your computer and use it in GitHub Desktop.
Simple Interpreter
Let x = 1
Let y = 3
Let z = 0
z = x + y
print[z]
package Interpreter;
/**
* Created by Sanitarium on 4/29/2016.
*/
import javafx.util.Pair;
import java.io.*;
import java.*;
import java.util.*;
public class Interpret {
public static void read()
{
try
{
File file = new File("C:\\Users\\Sanitarium\\IdeaProjects\\Interpreter\\src\\java\\Interpreter\\code.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line = null;
boolean var = false;
boolean operation = false;
//public static int x = 0; public static int y = 0; public static int z = 0;//variables
//List<Integer> values = new ArrayList<Integer>();
HashMap<String, Integer> ValuesMap = new HashMap<String,Integer>();
while ((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
//do this for each line........
String[] tokens = line.split(" ");
System.out.println(tokens.length);
int i = 0;
System.out.println(tokens[i]);
if(tokens[i].contentEquals("Let") && tokens[i+2].contentEquals("="))// upcoming variable
{
ValuesMap.put( tokens[i+1], Integer.parseInt( tokens[tokens.length-1] ) );
}
else if( ValuesMap.containsKey(tokens[i]) && tokens[i+1].contentEquals("=") )
{
int temp =0;
int lValue = ValuesMap.get(tokens[i+2]);
int RValue = ValuesMap.get(tokens[i+4]);
if (tokens[i+3].contentEquals("+"))
{
temp = lValue + RValue;
}
else if (tokens[i+3].contentEquals("-"))
{
temp = lValue - RValue;
}
ValuesMap.put(tokens[i], temp);
}
else if (tokens[i].contains("print"))
{
System.out.println(ValuesMap.get("z"));
}
}
fileReader.close();
System.out.println("-----------\n\nEOF!\n");
System.out.println(ValuesMap);
// System.out.println("list size"+values.size());
// for(int i=0; i<values.size(); i++)
// {
// System.out.println(values.get(i));
// }
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
read();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment