JavaCUP是Java语言实现的CUP解析器生成器。
示例代码:
//SimpleExampleScannerClass//scanner.javaimportjava_cup.runtime.*;importjava.io.*;//importsym;publicclassscannerimplementsjava_cup.runtime.Scanner{/*singlelookaheadcharacter*/protectedstaticintnext_char;//sincecupv11weuseSymbolFactoriesratherthanSymbolsprivateSymbolFactorysf=newDefaultSymbolFactory();privatestaticFileReaderfileReader;publicscanner(FileReaderfr){this.fileReader=fr;}/*advanceinputbyonecharacter*/protectedstaticvoidadvance()throwsjava.io.IOException{next_char=fileReader.read();}/*initializethescanner*/publicstaticvoidinit()throwsjava.io.IOException{advance();}/*recognizeandreturnthenextcompletetoken*/publicSymbolnext_token()throwsjava.io.IOException{for(;;)switch(next_char){case'0':case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':/*parseadecimalinteger*/inti_val=0;do{i_val=i_val*10+(next_char-'0');advance();}while(next_char>='0'&&next_char<='9');returnsf.newSymbol("NUMBER",sym.NUMBER,newInteger(i_val));case';':advance();returnsf.newSymbol("SEMI",sym.SEMI);case'+':advance();returnsf.newSymbol("PLUS",sym.PLUS);case'-':advance();returnsf.newSymbol("MINUS",sym.MINUS);case'*':advance();returnsf.newSymbol("TIMES",sym.TIMES);case'/':advance();returnsf.newSymbol("DIVIDE",sym.DIVIDE);case'%':advance();returnsf.newSymbol("MOD",sym.MOD);case'(':advance();returnsf.newSymbol("LPAREN",sym.LPAREN);case')':advance();returnsf.newSymbol("RPAREN",sym.RPAREN);case-1:returnsf.newSymbol("EOF",sym.EOF);default:/*inthissimplescannerwejustignoreeverythingelse*/advance();break;}}};
评论