⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 java.g

📁 Java写的词法/语法分析器。可生成JAVA语言或者是C++的词法和语法分析器。并可产生语法分析树和对该树进行遍历
💻 G
📖 第 1 页 / 共 2 页
字号:
	;// an exception handler try/catch blocktryBlock	:	"try"^ compoundStatement		(handler)*		( "finally"^ compoundStatement )?	;// an exception handlerhandler	:	"catch"^ LPAREN! parameterDeclaration RPAREN! compoundStatement	;// expressions// Note that most of these expressions follow the pattern//   thisLevelExpression ://       nextHigherPrecedenceExpression//           (OPERATOR nextHigherPrecedenceExpression)*// which is a standard recursive definition for a parsing an expression.// The operators in java have the following precedences://    lowest  (13)  = *= /= %= += -= <<= >>= >>>= &= ^= |=//            (12)  ?://            (11)  ||//            (10)  &&//            ( 9)  |//            ( 8)  ^//            ( 7)  &//            ( 6)  == !=//            ( 5)  < <= > >=//            ( 4)  << >>//            ( 3)  +(binary) -(binary)//            ( 2)  * / %//            ( 1)  ++ -- +(unary) -(unary)  ~  !  (type)//                  []   () (method call)  . (dot -- identifier qualification)//                  new   ()  (explicit parenthesis)//// the last two are not usually on a precedence chart; I put them in// to point out that new has a higher precedence than '.', so you// can validy use//     new Frame().show()// // Note that the above precedence levels map to the rules below...// Once you have a precedence chart, writing the appropriate rules as below//   is usually very straightfoward// the mother of all expressionsexpression	:	assignmentExpression		{#expression = #(#[EXPR,"EXPR"],#expression);}	;// This is a list of expressions.expressionList	:	expression (COMMA! expression)*		{#expressionList = #(#[ELIST,"ELIST"], expressionList);}	;// assignment expression (level 13)assignmentExpression	:	conditionalExpression		(	(	ASSIGN^            |   PLUS_ASSIGN^            |   MINUS_ASSIGN^            |   STAR_ASSIGN^            |   DIV_ASSIGN^            |   MOD_ASSIGN^            |   SR_ASSIGN^            |   BSR_ASSIGN^            |   SL_ASSIGN^            |   BAND_ASSIGN^            |   BXOR_ASSIGN^            |   BOR_ASSIGN^            )			assignmentExpression		)?	;// conditional test (level 12)conditionalExpression	:	logicalOrExpression		( QUESTION^ assignmentExpression COLON! conditionalExpression )?	;// logical or (||)  (level 11)logicalOrExpression	:	logicalAndExpression (LOR^ logicalAndExpression)*	;// logical and (&&)  (level 10)logicalAndExpression	:	inclusiveOrExpression (LAND^ inclusiveOrExpression)*	;// bitwise or non-short-circuiting or (|)  (level 9)inclusiveOrExpression	:	exclusiveOrExpression (BOR^ exclusiveOrExpression)*	;// exclusive or (^)  (level 8)exclusiveOrExpression	:	andExpression (BXOR^ andExpression)*	;// bitwise or non-short-circuiting and (&)  (level 7)andExpression	:	equalityExpression (BAND^ equalityExpression)*	;// equality/inequality (==/!=) (level 6)equalityExpression	:	relationalExpression ((NOT_EQUAL^ | EQUAL^) relationalExpression)*	;// boolean relational expressions (level 5)relationalExpression	:	shiftExpression		(	(	(	LT^				|	GT^				|	LE^				|	GE^				)				shiftExpression			)*		|	"instanceof"^ typeSpec[true]		)	;// bit shift expressions (level 4)shiftExpression	:	additiveExpression ((SL^ | SR^ | BSR^) additiveExpression)*	;// binary addition/subtraction (level 3)additiveExpression	:	multiplicativeExpression ((PLUS^ | MINUS^) multiplicativeExpression)*	;// multiplication/division/modulo (level 2)multiplicativeExpression	:	unaryExpression ((STAR^ | DIV^ | MOD^ ) unaryExpression)*	;unaryExpression	:	INC^ unaryExpression	|	DEC^ unaryExpression	|	MINUS^ {#MINUS.setType(UNARY_MINUS);} unaryExpression	|	PLUS^  {#PLUS.setType(UNARY_PLUS);} unaryExpression	|	unaryExpressionNotPlusMinus	;unaryExpressionNotPlusMinus	:	BNOT^ unaryExpression	|	LNOT^ unaryExpression	|	(	// subrule allows option to shut off warnings			options {				// "(int" ambig with postfixExpr due to lack of sequence				// info in linear approximate LL(k).  It's ok.  Shut up.				generateAmbigWarnings=false;			}		:	// If typecast is built in type, must be numeric operand			// Also, no reason to backtrack if type keyword like int, float...			lpb:LPAREN^ {#lpb.setType(TYPECAST);} builtInTypeSpec[true] RPAREN!			unaryExpression			// Have to backtrack to see if operator follows.  If no operator			// follows, it's a typecast.  No semantic checking needed to parse.			// if it _looks_ like a cast, it _is_ a cast; else it's a "(expr)"		|	(LPAREN classTypeSpec[true] RPAREN unaryExpressionNotPlusMinus)=>			lp:LPAREN^ {#lp.setType(TYPECAST);} classTypeSpec[true] RPAREN!			unaryExpressionNotPlusMinus		|	postfixExpression		)	;// qualified names, array expressions, method invocation, post inc/decpostfixExpression	:	primaryExpression // start with a primary		(	// qualified id (id.id.id.id...) -- build the name			DOT^ ( IDENT				| "this"				| "class"				| newExpression				| "super" LPAREN ( expressionList )? RPAREN				)			// the above line needs a semantic check to make sure "class"			//   is the _last_ qualifier.			// allow ClassName[].class		|	( lbc:LBRACK^ {#lbc.setType(ARRAY_DECLARATOR);} RBRACK! )+			DOT^ "class"			// an array indexing operation		|	lb:LBRACK^ {#lb.setType(INDEX_OP);} expression RBRACK!			// method invocation			// The next line is not strictly proper; it allows x(3)(4) or			//  x[2](4) which are not valid in Java.  If this grammar were used			//  to validate a Java program a semantic check would be needed, or			//   this rule would get really ugly...		|	lp:LPAREN^ {#lp.setType(METHOD_CALL);}				argList			RPAREN!		)*		// possibly add on a post-increment or post-decrement.		// allows INC/DEC on too much, but semantics can check		(	in:INC^ {#in.setType(POST_INC);}	 	|	de:DEC^ {#de.setType(POST_DEC);}		|	// nothing		)		// look for int.class and int[].class	|	builtInType 		( lbt:LBRACK^ {#lbt.setType(ARRAY_DECLARATOR);} RBRACK! )*		DOT^ "class"	;// the basic element of an expressionprimaryExpression	:	IDENT	|	newExpression	|	constant	|	"super"	|	"true"	|	"false"	|	"this"	|	"null"	|	LPAREN! assignmentExpression RPAREN!	;/** object instantiation. *  Trees are built as illustrated by the following input/tree pairs: *   *  new T() *   *  new *   | *   T --  ELIST *           | *          arg1 -- arg2 -- .. -- argn *   *  new int[] * *  new *   | *  int -- ARRAY_DECLARATOR *   *  new int[] {1,2} * *  new *   | *  int -- ARRAY_DECLARATOR -- ARRAY_INIT *                                  | *                                EXPR -- EXPR *                                  |      | *                                  1      2 *   *  new int[3] *  new *   | *  int -- ARRAY_DECLARATOR *                | *              EXPR *                | *                3 *   *  new int[1][2] *   *  new *   | *  int -- ARRAY_DECLARATOR *               | *         ARRAY_DECLARATOR -- EXPR *               |              | *             EXPR             1 *               | *               2 *   */newExpression	:	"new"^ type		(	LPAREN! argList RPAREN! (classBlock)?			//java 1.1			// Note: This will allow bad constructs like			//    new int[4][][3] {exp,exp}.			//    There needs to be a semantic check here...			// to make sure:			//   a) [ expr ] and [ ] are not mixed			//   b) [ expr ] and an init are not used together		|	newArrayDeclarator (arrayInitializer)?		)	;argList	:	(	expressionList		|	/*nothing*/			{#argList = #[ELIST,"ELIST"];}		)	;newArrayDeclarator	:	(			// CONFLICT:			// newExpression is a primaryExpression which can be			// followed by an array index reference.  This is ok,			// as the generated code will stay in this loop as			// long as it sees an LBRACK (proper behavior)			options {				warnWhenFollowAmbig = false;			}		:			lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);}				(expression)?			RBRACK!		)+	;constant	:	NUM_INT	|	CHAR_LITERAL	|	STRING_LITERAL	|	NUM_FLOAT	;//----------------------------------------------------------------------------// The Java scanner//----------------------------------------------------------------------------class JavaLexer extends Lexer;options {	exportVocab=Java;      // call the vocabulary "Java"	testLiterals=false;    // don't automatically test for literals	k=4;                   // four characters of lookahead}// OPERATORSQUESTION		:	'?'		;LPAREN			:	'('		;RPAREN			:	')'		;LBRACK			:	'['		;RBRACK			:	']'		;LCURLY			:	'{'		;RCURLY			:	'}'		;COLON			:	':'		;COMMA			:	','		;//DOT			:	'.'		;ASSIGN			:	'='		;EQUAL			:	"=="	;LNOT			:	'!'		;BNOT			:	'~'		;NOT_EQUAL		:	"!="	;DIV				:	'/'		;DIV_ASSIGN		:	"/="	;PLUS			:	'+'		;PLUS_ASSIGN		:	"+="	;INC				:	"++"	;MINUS			:	'-'		;MINUS_ASSIGN	:	"-="	;DEC				:	"--"	;STAR			:	'*'		;STAR_ASSIGN		:	"*="	;MOD				:	'%'		;MOD_ASSIGN		:	"%="	;SR				:	">>"	;SR_ASSIGN		:	">>="	;BSR				:	">>>"	;BSR_ASSIGN		:	">>>="	;GE				:	">="	;GT				:	">"		;SL				:	"<<"	;SL_ASSIGN		:	"<<="	;LE				:	"<="	;LT				:	'<'		;BXOR			:	'^'		;BXOR_ASSIGN		:	"^="	;BOR				:	'|'		;BOR_ASSIGN		:	"|="	;LOR				:	"||"	;BAND			:	'&'		;BAND_ASSIGN		:	"&="	;LAND			:	"&&"	;SEMI			:	';'		;// Whitespace -- ignoredWS	:	(	' '		|	'\t'		|	'\f'		// handle newlines		|	(	"\r\n"  // Evil DOS			|	'\r'    // Macintosh			|	'\n'    // Unix (the right way)			)			{ newline(); }		)		{ _ttype = Token.SKIP; }	;// Single-line commentsSL_COMMENT	:	"//"		(~('\n'|'\r'))* ('\n'|'\r'('\n')?)		{$setType(Token.SKIP); newline();}	;// multiple-line commentsML_COMMENT	:	"/*"		(	/*	'\r' '\n' can be matched in one alternative or by matching				'\r' in one iteration and '\n' in another.  I am trying to				handle any flavor of newline that comes in, but the language				that allows both "\r\n" and "\r" and "\n" to all be valid				newline is ambiguous.  Consequently, the resulting grammar				must be ambiguous.  I'm shutting this warning off.			 */			options {				generateAmbigWarnings=false;			}		:			{ LA(2)!='/' }? '*'		|	'\r' '\n'		{newline();}		|	'\r'			{newline();}		|	'\n'			{newline();}		|	~('*'|'\n'|'\r')		)*		"*/"		{$setType(Token.SKIP);}	;// character literalsCHAR_LITERAL	:	'\'' ( ESC | ~'\'' ) '\''	;// string literalsSTRING_LITERAL	:	'"' (ESC|~('"'|'\\'))* '"'	;// escape sequence -- note that this is protected; it can only be called//   from another lexer rule -- it will not ever directly return a token to//   the parser// There are various ambiguities hushed in this rule.  The optional// '0'...'9' digit matches should be matched here rather than letting// them go back to STRING_LITERAL to be matched.  ANTLR does the// right thing by matching immediately; hence, it's ok to shut off// the FOLLOW ambig warnings.protectedESC	:	'\\'		(	'n'		|	'r'		|	't'		|	'b'		|	'f'		|	'"'		|	'\''		|	'\\'		|	('u')+ HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT 		|	('0'..'3')			(				options {					warnWhenFollowAmbig = false;				}			:	('0'..'7')				(						options {						warnWhenFollowAmbig = false;					}				:	'0'..'7'				)?			)?		|	('4'..'7')			(				options {					warnWhenFollowAmbig = false;				}			:	('0'..'9')			)?		)	;// hexadecimal digit (again, note it's protected!)protectedHEX_DIGIT	:	('0'..'9'|'A'..'F'|'a'..'f')	;// a dummy rule to force vocabulary to be all characters (except special//   ones that ANTLR uses internally (0 to 2)protectedVOCAB	:	'\3'..'\377'	;// an identifier.  Note that testLiterals is set to true!  This means// that after we match the rule, we look in the literals table to see// if it's a literal or really an identiferIDENT	options {testLiterals=true;}	:	('a'..'z'|'A'..'Z'|'_'|'$') ('a'..'z'|'A'..'Z'|'_'|'0'..'9'|'$')*	;// a numeric literalNUM_INT	{boolean isDecimal=false;}	:	'.' {_ttype = DOT;}			(('0'..'9')+ (EXPONENT)? (FLOAT_SUFFIX)? { _ttype = NUM_FLOAT; })?	|	(	'0' {isDecimal = true;} // special case for just '0'			(	('x'|'X')				(											// hex					// the 'e'|'E' and float suffix stuff look					// like hex digits, hence the (...)+ doesn't					// know when to stop: ambig.  ANTLR resolves					// it correctly by matching immediately.  It					// is therefor ok to hush warning.					options {						warnWhenFollowAmbig=false;					}				:	HEX_DIGIT				)+			|	('0'..'7')+									// octal			)?		|	('1'..'9') ('0'..'9')*  {isDecimal=true;}		// non-zero decimal		)		(	('l'|'L')				// only check to see if it's a float if looks like decimal so far		|	{isDecimal}?			(	'.' ('0'..'9')* (EXPONENT)? (FLOAT_SUFFIX)?			|	EXPONENT (FLOAT_SUFFIX)?			|	FLOAT_SUFFIX			)			{ _ttype = NUM_FLOAT; }		)?	;// a couple protected methods to assist in matching floating point numbersprotectedEXPONENT	:	('e'|'E') ('+'|'-')? ('0'..'9')+	;protectedFLOAT_SUFFIX	:	'f'|'F'|'d'|'D'	;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -