Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ultrasimplistic example of a mini/micro compiler that validates a sentence starting with "hombres" and finishing with "tal"
import java.text.ParseException;
class Lexer {
String [] tokens;
void tokenize( String input ) {
tokens = input.split("\\s");
}
}
class Parser {
void parse( String [] tokens ) throws ParseException {
// la regla es que empieze con "hombres" y termine con "tal"
if ( tokens == null
|| tokens.length == 0
|| !tokens[0].equals("hombres")
|| !tokens[tokens.length-1].equals("tal") ) {
throw new ParseException("<hombres> expected at the beginning or <tal> at the end."+tokens[tokens.length-1], 0);
}
/// todo ok
}
}
class CodeGenerator {
String [] transform( String [] tokens ) {
String [] output = new String[tokens.length];
int i = 0;
StringBuilder sb = new StringBuilder();
for ( String token : tokens ) {
output[i++] = sb.append(token).reverse().toString();
sb.setLength(0);
}
return output;
}
}
class Main {
public static void main( String ... args ) throws ParseException {
Lexer l = new Lexer();
l.tokenize( args[0] );
Parser p = new Parser();
p.parse( l.tokens );
CodeGenerator g = new CodeGenerator();
for ( String s : g.transform( l.tokens ) ) {
System.out.print(s);
System.out.print(' ');
}
System.out.println();
}
}
@alain8915

This comment has been minimized.

Show comment
Hide comment
@alain8915

alain8915 May 25, 2016

i have a Java error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at l.tokenize( args[0] );

how can i fix it??

i have a Java error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at l.tokenize( args[0] );

how can i fix it??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment