-
Notifications
You must be signed in to change notification settings - Fork 0
/
Compiler.java
121 lines (109 loc) · 2.63 KB
/
Compiler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import java.lang.Exception;
import java.lang.StringBuilder;
import java.lang.Character;
import java.lang.String;
import java.lang.System;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Scanner;
public class Compiler{
public static final ArrayList<String> commands = new ArrayList<String>();
public static final int[] nodes = new int[1000];
public static int node = (int)(nodes.length / 2);
public static void main(String[] args){
if ( args.length != 0 )
new Compiler(args);
else
//assert false;
return;
}
public Compiler(String[] args){
if ( setCommands(readFile(args[0])) ){
parseCommands(0, Compiler.commands.size());
}
}
public String readFile(String file){
try{
StringBuilder s = new StringBuilder("");
String temp = "";
BufferedReader r = new BufferedReader(new FileReader(file));
while( (temp = r.readLine()) != null ){ // O(n) = n
s.append(temp);
}
r.close();
return s.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public boolean setCommands(String c){
String[] sep = c.split("");
int i = 0;
for ( String a : sep )
if ( a.equals("<") || a.equals(">") || a.equals("+") || a.equals("-") || a.equals(".") || a.equals("[") || a.equals("]") || a.equals(",") ){
Compiler.commands.add( a );
i++;
}
return true;
}
public boolean parseCommands(int s, int e){
try{
String c = "";
int t = 0;
String in="";
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
for ( int i = s; i <= e; i++ ) {
if(Compiler.commands.size() == i)
break;
c = Compiler.commands.get(i);
switch (c){
case ">":
Compiler.node++;
break;
case "<":
Compiler.node--;
break;
case "+":
Compiler.nodes[Compiler.node]++;
break;
case "-":
Compiler.nodes[Compiler.node]--;
break;
case ",":
in = sc.readLine();
if (in.length() > 1){
assert false;
}
Compiler.nodes[Compiler.node] = (int)(in.charAt(0));
break;
case ".":
System.out.println( Character.toString((char)Compiler.nodes[Compiler.node]));
break;
}
if(c.equals("[")){
for ( int k = i; k < Compiler.commands.size(); k++ ){
if( Compiler.commands.get(k).equals("]") ){
t = k;
break;
}
}
parseCommands(i + 1, t);
i = t ;
}
if(c.equals("]") ){
if( Compiler.nodes[Compiler.node] == 0 ){
break;
}
else{
parseCommands( s, e );
}
}
}
sc.close();
}catch(Exception err){ err.printStackTrace(); }
return true;
}
}