Created
September 24, 2013 16:39
-
-
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"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i have a Java error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at l.tokenize( args[0] );
how can i fix it??