aboutsummaryrefslogtreecommitdiff
path: root/gunit/src/main/antlr3/org/antlr/gunit/gUnit.g
blob: 5a3e269b12c9c9b050fe1d14093515a1151462e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
[The "BSD licence"]
Copyright (c) 2007-2008 Leon Jen-Yuan Su
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar gUnit;
options {language=Java;}
tokens {
	OK = 'OK';
	FAIL = 'FAIL';
	DOC_COMMENT;
}
@header {package org.antlr.gunit;}
@lexer::header {
package org.antlr.gunit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
}
@members {
public GrammarInfo grammarInfo;
public gUnitParser(TokenStream input, GrammarInfo grammarInfo) {
	super(input);
	this.grammarInfo = grammarInfo;
}
}

gUnitDef:	'gunit' g1=id ('walks' g2=id)? ';' 
		{
		if ( $g2.text!=null ) {
			grammarInfo.setGrammarName($g2.text);
			grammarInfo.setTreeGrammarName($g1.text);
		}
		else {
			grammarInfo.setGrammarName($g1.text);
		}
		}
		optionsSpec? header? testsuite*
	;
	
optionsSpec 
	:	OPTIONS (option ';')+ '}'
	;

// Note: currently, this is the only valid option for setting customized tree adaptor	
option	:	id '=' treeAdaptor
		{
		if ( $id.text.equals("TreeAdaptor") ) {
		    grammarInfo.setAdaptor($treeAdaptor.text);
		}
		// TODO: need a better error logging strategy
		else System.err.println("Invalid option detected: "+$text);
		}
	;
	
treeAdaptor
	:	id EXT*
	;

header	:	'@header' ACTION
		{
		int pos1, pos2;
		if ( (pos1=$ACTION.text.indexOf("package"))!=-1 && (pos2=$ACTION.text.indexOf(';'))!=-1 ) {
			grammarInfo.setGrammarPackage($ACTION.text.substring(pos1+8, pos2).trim());	// substring the package path
		}
		else {
			System.err.println("error(line "+$ACTION.getLine()+"): invalid header");
		}
		}
	;
		
testsuite	// gUnit test suite based on individual rule
scope {
boolean isLexicalRule;
}
@init {
gUnitTestSuite ts = null;
$testsuite::isLexicalRule = false;
}
	:	(	r1=RULE_REF ('walks' r2=RULE_REF)? 
			{
			if ( $r2==null ) ts = new gUnitTestSuite($r1.text);
			else ts = new gUnitTestSuite($r1.text, $r2.text);
			}
		|	t=TOKEN_REF 
			{
			ts = new gUnitTestSuite();
			ts.setLexicalRuleName($t.text);
			$testsuite::isLexicalRule = true;
			}
		)
		':'
		testcase[ts]+ {grammarInfo.addRuleTestSuite(ts);}
	;

// TODO : currently gUnit just ignores illegal test for lexer rule, but should also emit a reminding message
testcase[gUnitTestSuite ts]	// individual test within a (rule)testsuite
	:	input expect {$ts.addTestCase($input.in, $expect.out);}
	;

input returns [gUnitTestInput in]
@init {
String testInput = null;
boolean inputIsFile = false;
int line = -1;
}
@after {
in = new gUnitTestInput(testInput, inputIsFile, line);
}
	:	STRING 
		{
		testInput = $STRING.text.replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t")
		.replace("\\b", "\b").replace("\\f", "\f").replace("\\\"", "\"").replace("\\'", "\'").replace("\\\\", "\\");
		line = $STRING.line;
		}
	|	ML_STRING
		{
		testInput = $ML_STRING.text;
		line = $ML_STRING.line;
		}
	|	file
		{
		testInput = $file.text;
		inputIsFile = true;
		line = $file.line;
		}
	;
	
expect returns [AbstractTest out]
	:	OK {$out = new BooleanTest(true);}
	|	FAIL {$out = new BooleanTest(false);}
	|	'returns' RETVAL {if ( !$testsuite::isLexicalRule ) $out = new ReturnTest($RETVAL);}
	|	'->' output {if ( !$testsuite::isLexicalRule ) $out = new OutputTest($output.token);}
	;

output returns [Token token]
	:	STRING 
		{
		$STRING.setText($STRING.text.replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t")
		.replace("\\b", "\b").replace("\\f", "\f").replace("\\\"", "\"").replace("\\'", "\'").replace("\\\\", "\\"));
		$token = $STRING;
		}
	|	ML_STRING {$token = $ML_STRING;}
	|	AST {$token = $AST;}
	|	ACTION {$token = $ACTION;}
	;

file returns [int line]	
	:	id EXT? {$line = $id.line;}
	;

id returns [int line] 
	:	TOKEN_REF {$line = $TOKEN_REF.line;}
	|	RULE_REF {$line = $RULE_REF.line;}
	;

// L E X I C A L   R U L E S

SL_COMMENT
 	:	'//' ~('\r'|'\n')* '\r'? '\n' {$channel=HIDDEN;}
	;

ML_COMMENT
	:	'/*' {$channel=HIDDEN;} .* '*/'
	;

STRING	:	'"' ( ESC | ~('\\'|'"') )* '"' {setText(getText().substring(1, getText().length()-1));}
	;

ML_STRING
	:	{// we need to determine the number of spaces or tabs (indentation) for multi-line input
		StringBuffer buf = new StringBuffer();
		int i = -1;
		int c = input.LA(-1);
		while ( c==' ' || c=='\t' ) {
			buf.append((char)c);
			c = input.LA(--i);
		}
		String indentation = buf.reverse().toString();
		}
		'<<' .* '>>' 
		{// also determine the appropriate newline separator and get info of the first and last 2 characters (exclude '<<' and '>>')
		String newline = System.getProperty("line.separator");
		String front, end;
		int oldFrontIndex = 2;
		int oldEndIndex = getText().length()-2;
		int newFrontIndex, newEndIndex;
		if ( newline.length()==1 ) {
			front = getText().substring(2, 3);
			end = getText().substring(getText().length()-3, getText().length()-2);
			newFrontIndex = 3;
			newEndIndex = getText().length()-3;
		}
		else {// must be 2, e.g. Windows System which uses \r\n as a line separator
			front = getText().substring(2, 4);
			end = getText().substring(getText().length()-4, getText().length()-2);
			newFrontIndex = 4;
			newEndIndex = getText().length()-4;
		}
		// strip unwanted characters, e.g. '<<' (including a newline after it) or '>>'  (including a newline before it)
		String temp = null;
		if ( front.equals(newline) && end.equals(newline) ) {
			// need to handle the special case: <<\n>> or <<\r\n>>
			if ( newline.length()==1 && getText().length()==5 ) temp = "";
			else if ( newline.length()==2 && getText().length()==6 ) temp = "";
			else temp = getText().substring(newFrontIndex, newEndIndex);
		}
		else if ( front.equals(newline) ) {
			temp = getText().substring(newFrontIndex, oldEndIndex);
		}
		else if ( end.equals(newline) ) {
			temp = getText().substring(oldFrontIndex, newEndIndex);
		}
		else {
			temp = getText().substring(oldFrontIndex, oldEndIndex);
		}
		// finally we need to prpcess the indentation line by line
		BufferedReader bufReader = new BufferedReader(new StringReader(temp));
		buf = new StringBuffer();
		String line = null;
		int count = 0;
		try {
			while((line = bufReader.readLine()) != null) {
				if ( line.startsWith(indentation) ) line = line.substring(indentation.length());
				if ( count>0 ) buf.append(newline);
				buf.append(line);
				count++;
			}
			setText(buf.toString());
		}
		catch (IOException ioe) {
			setText(temp);
		}
		}
	;

TOKEN_REF
	:	'A'..'Z' ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
	;

RULE_REF
	:	'a'..'z' ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
	;

EXT	:	'.'('a'..'z'|'A'..'Z'|'0'..'9')+;

RETVAL	:	NESTED_RETVAL {setText(getText().substring(1, getText().length()-1));}
	;

fragment
NESTED_RETVAL :
	'['
	(	options {greedy=false;}
	:	NESTED_RETVAL
	|	.
	)*
	']'
	;

AST	:	NESTED_AST (' '? NESTED_AST)*;

fragment
NESTED_AST :
	'('
	(	NESTED_AST
	|   STRING_LITERAL
	|	~('('|')'|'"')
	)*
	')'
	;

OPTIONS	:	'options' WS* '{'
	;

ACTION
	:	NESTED_ACTION {setText(getText().substring(1, getText().length()-1));}
	;

fragment
NESTED_ACTION :
	'{'
	(	options {greedy=false; k=3;}
	:	NESTED_ACTION
	|	STRING_LITERAL
	|	CHAR_LITERAL
	|	.
	)*
	'}'
	;

fragment
CHAR_LITERAL
	:	'\'' ( ESC | ~('\''|'\\') ) '\''
	;

fragment
STRING_LITERAL
	:	'"' ( ESC | ~('\\'|'"') )* '"'
	;

fragment
ESC	:	'\\'
		(	'n'
		|	'r'
		|	't'
		|	'b'
		|	'f'
		|	'"'
		|	'\''
		|	'\\'
		|	'>'
		|	'u' XDIGIT XDIGIT XDIGIT XDIGIT
		|	. // unknown, leave as it is
		)
	;
	
fragment
XDIGIT :
		'0' .. '9'
	|	'a' .. 'f'
	|	'A' .. 'F'
	;

WS	:	(	' '
		|	'\t'
		|	'\r'? '\n'
		)+
		{$channel=HIDDEN;}
	;