Skip to content

Instantly share code, notes, and snippets.

@fgoinai
Created May 14, 2017 12:55
Show Gist options
  • Save fgoinai/3902c5ff00abcd396f0a1bab88f94470 to your computer and use it in GitHub Desktop.
Save fgoinai/3902c5ff00abcd396f0a1bab88f94470 to your computer and use it in GitHub Desktop.
I think this is a praser, I hope.
//FuckTokenStream
import java.io.*;
public class FuckTokenStream implements TokenStream {
private BufferedReader br;
private int pos = 0;
private char[] cache;
FuckTokenStream(InputStream is) {
this.br = new BufferedReader(new InputStreamReader(is));
getStmtBuf(br);
}
private void getStmtBuf(BufferedReader br) {
try {
cache = br.readLine().toCharArray();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public Token getToken() throws IOException {
if (pos >= cache.length) return new Token(Token.TokenType.NONE, null);
while (cache[pos] == ' ') consumeToken();
Token tmp = matcher(cache[pos]);
if (tmp.tokenType != Token.TokenType.INT) {
return tmp;
} else {
Token ret = tmp;
int buf = (int) ret.value;
int off = 1;
while ((pos + off) < cache.length &&
(tmp = matcher(cache[pos + off])) != null &&
tmp.tokenType == Token.TokenType.INT) {
buf *= 10;
buf += (int) tmp.value;
ret = new Token(Token.TokenType.INT, buf);
off++;
}
pos += off - 1;
return ret;
}
}
@Override
public void consumeToken() {
pos++;
}
private Token matcher(char var) throws IOException {
switch (var) {
case '(':
return new Token(Token.TokenType.LPAR, var);
case ')':
return new Token(Token.TokenType.RPAR, var);
case '+':
return new Token(Token.TokenType.PLUS, var);
case '-':
return new Token(Token.TokenType.MINUS, var);
case '*':
return new Token(Token.TokenType.MULT, var);
case '/':
return new Token(Token.TokenType.DIV, var);
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
return new Token(Token.TokenType.INT, Character.getNumericValue(var));
case '\n':
return new Token(Token.TokenType.NONE, var);
default:
return null;
}
}
}
//Token
class Token {
public enum TokenType {
LPAR, RPAR,
PLUS,
MINUS,
MULT,
DIV,
INT,
NONE,
}
TokenType tokenType;
Object value;
Token(TokenType tt, Object v) {
this.tokenType = tt;
this.value = v;
}
}
//main
public class Main {
public static void main(String[] args) {
TokenStream ts = new FuckTokenStream(System.in);
try {
Token tmp;
while ((tmp = ts.getToken()).tokenType != Token.TokenType.NONE) {
if (tmp.value != null) {
System.out.println(tmp.tokenType + " " + tmp.value);
}
ts.consumeToken();
}
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment