Skip to content

Instantly share code, notes, and snippets.

@oscarryz
Created September 24, 2013 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oscarryz/6687505 to your computer and use it in GitHub Desktop.
Save oscarryz/6687505 to your computer and use it in GitHub Desktop.
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
Copy link

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