- Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathjava_syntax.py
More file actions
Latest commit
417 lines (368 loc) · 15.3 KB
/
Copy pathjava_syntax.py
File metadata and controls
417 lines (368 loc) · 15.3 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/usr/bin/python3
importre
"""
TODO for indentations:
1: handle inline-if/while/do loops correctly
2: prevent multiple indents on a single line
3: look for implied line continuations
4: switch
1:
- e.g. if()\nFOO; should indent FOO;
- this can occur after if(...), else, while(...), do
- likely implementation: put items on stack, delete all topmost
inline blocks when a ; or } is processed
- make sure if()\nif()\nelse is indented logically!
such an else should only close the latest if()
- if()\s*[not {] denotes the start of an inline-if, but the indent
should be counted as starting right after the parenthesis
2:
- e.g. {{\nFOO should indent FOO by only one level
- similar with for() for() {\n...
3:
- maybe ; and } and , are the non-continuing characters?
4:
- inside of switch(){...} is indented by 2,
but lines starting with 'symbol:' get indented only by 1.
test cases for 1+2: 'for()for()\n{\nFOO' should give
for()for()
{
FOO
while 'x = {{foo,\nbar},\nbaz};' should give
x = {{foo,
bar},
baz};
"""
defrecord(**dict):
""" e.g. foo = record(bar='baz', jim=5) creates an object foo
such that foo.bar == 'baz', foo.jim == 5 """
returntype('', (), dict)
# parser states
java, scomment, mcomment, squote, dquote= [
record(name=n) fornin [
"JAVA", "SINGLE-LINE COMMENT", "MULTI-LINE COMMENT",
"SINGLE-QUOTED LITERAL", "DOUBLE-QUOTED LITERAL"]]
defis_comment(state): returnstatein {scomment, mcomment}
whitespace= {' ', '\t', '\f', '\n'}
open_parens= {'{', '(', '['}
close_parens= {'}', ')', ']'}
match= {'{':'}', '}':'{', '(':')', ')':'(', '[':']', ']':'['}
paren_name= {'{':'brace', '[':'bracket', '(':'parenthesis'}
forpinopen_parens: paren_name[match[p]] =paren_name[p]
default_tab_width=4
defjava_parse(rawtext):
"""
Procedure to check whether a snippet of Java 7 text represents
a single line, a properly nested {} block structure, or none of the above.
A single line is defined as having no newline or semicolon outside of
comments/quotes. This is not the absolute best definition as you could
write something like
do {} while (true) or if (x == y++) {} else if (y == z++) {}
but it does eliminate for-loops and therefore all comma-delimeted
expression sequences. If you solve an exercise in such a crazy way,
props to you!
The text is said to be well-terminated if the last non-comment character
is ; or }. Otherwise it returns a 'terminated badly' flag. This is
mostly to avoid students doing sneaky things where we ask them to
fill in a spot and then they get it to interact with surrounding fixed
text. E.g., 'x =' on one line followed by our 'y = input()' on the next.
Reference:
http://docs.oracle.com/javase/specs/jls/se7/html/index.html
About preprocessing:
We convert all \r\n, \n\r, and isolated \r to \n, to simplify the logic.
Java allows you to write \uABCD where ABCD are hex digits as a
replacement for any part of your source text, including comments, javadoc,
quotes, and actual language structures. For example you
can start a comment with \* and end it with \u002a\ since unicode code
point 42 is an asterisk. This makes our job harder. The first thing is to
take care of this with preprocessing. We'll only deal with true ASCII (code
points < 128) since all meaningful Java language characters lie in this
range, and since dealing with higher ones is a pain in PHP.
"""
defpreprocess(rawtext):
# not backslash, then 2k+1 backslashes, u's, 00, two hex digits
# nb: r"..." is a raw string to reduce backslash duplication
tmp=re.sub(
r"(?<!\\)((\\\\)*)\\u+00([0-7][0-9A-Fa-f])",
# on the next line mo is a match object #
lambdamo: mo.group(1) +chr(int(mo.group(3), 16)),
rawtext)
# normalize newlines. note 0x2028, 2029, 0085 are not valid in Java
tmp=re.sub("\n\r|\r\n|\r", "\n", tmp)
returntmp
defreport_error(description, no_pos=False):
nonlocalerrmsg
iferrmsg=="":
ifno_pos:
errmsg=description
else:
errmsg="Error at line {}, column {}:\n{}".format(
line, column, description)
deftabify_output_list(keep_comments, tab_width):
result= []
line= []
foriteminoutput_list:
ifitem.type=='text':
ifitem.chars=='\n':
pass# handled by 'indent'
# although it may add '\n' to very end
elifnotkeep_commentsanditem.is_comment:
pass
eliflen(line)==0anditem.charsinwhitespace:
pass# kill leading spaces
else:
line.append(item.chars)
elifitem.type=='indent':
# suppress blank lines if comments are off
ifkeep_commentsorlen(line) >0:
result.append(" "*tab_width*item.indent)
result.extend(line)
result.append('\n')
line= []
else: assertFalse, "unknown type "+str(item.type)+"in tabify"
return''.join(result)
defget_text(keep_comments=True, tabify=False, tab_width=default_tab_width):
iftabify:
returntabify_output_list(keep_comments=keep_comments,
tab_width=tab_width)
else:
ifkeep_comments:
returntext
else:
return''.join(i.charsforiinoutput_list
ifi.type=='text'andnoti.is_whitespace)
defregister_newline():
nonlocaloutput_list
output_list.append(record(type='indent', indent=line_indent))
### here are the variables that are not semantically constant ###
semicolons=0
errmsg=""
output_list= [] # list of characters and metadata used for output
position=0
state=java
nesting_stack= []
line=0
column=0
# line_indent is a running minimum of len(nesting_stack) on the current line
line_indent=0
text=preprocess(rawtext)
### begin the parsing loop
whileposition<len(text):
# define old.state, old.position
old=record(position=position, state=state)
ch=text[position]
is_newline= (ch=="\n") # \r was removed in preprocessing
nextch="NA"if (position+1==len(text)) elsetext[position+1]
digram=ch+nextch
position+=1
ifstate==java:
# begin case-checking
ifchinopen_parens:
nesting_stack.append(ch)
elifchinclose_parens:
iflen(nesting_stack) ==0:
report_error(
"Found a closing '{}' not matching any earlier '{}'.".
format(ch, match[ch]))
elifnesting_stack[-1] !=match[ch]:
report_error(
"Found a closing '{}' where a '{}' was expected.".
format(ch, match[nesting_stack[-1]]))
else:
nesting_stack.pop()
elifch=='"':
state=dquote
elifch=="'":
state=squote
elifdigram=='//':
state=scomment
position+=1
elifdigram=='/*':
state=mcomment
mcomment_start_line=line
position+=1
elifch==';':
semicolons+=1
# end of checking from 'java' state
elifstate==dquote:
ifis_newline:
report_error('String delimiter (") followed by end of line.')
elifdigramin {r"\\", r'\"'}:
position+=1
elifch=='"':
state=java
elifstate==squote:
ifis_newline:
report_error(
"Character delimiter (') followed by end of line.")
elifdigramin {r"\\", r"\'"}:
position+=1
elifch=="'":
state=java
elifstate==scomment:
ifis_newline:
state=java
elifstate==mcomment:
ifdigram=="*/":
state=java
position+=1
ifmcomment_start_line==line:
# fake whitespace! not pretty, but practical.
# this is to avoid tokens/* */collapsing.
# who really uses a one-line/* */anyway?
output_list.append(record(type='text',
chars=' ',
is_comment=False))
# continue parsing the next iteration!
ifis_newline:
register_newline()
line+=1
column=0
line_indent=len(nesting_stack)
else:
column+=position-old.position
line_indent=min(line_indent, len(nesting_stack))
output_list.append(record(
type='text',
chars=text[old.position:position],
is_comment= ((is_comment(state) oris_comment(old.state))
andnot (state==javaandold.state==scomment))
))
# parsing loop is done
ifstate==squote:
report_error("Character delimiter (') not followed by a matching end quote.", True)
elifstate==dquote:
report_error("String delimiter (\") not followed by a matching end quote.", True)
elifstate==mcomment:
report_error("Comment delimiter (/*) not followed by a matching end delimiter (*/).", True)
eliflen(nesting_stack) >0:
report_error("Opening '{}' not followed by a matching closing '{}'.".format(
nesting_stack[-1], match[nesting_stack[-1]]), True)
register_newline()
result= {}
valid=errmsg==""
last_significant_char=None
foriteminreversed(output_list):
ifitem.type!='text': continue
ifitem.charsinwhitespace: continue
ifitem.is_comment: continue
last_significant_char=item.chars[-1:]
break
returnrecord(
errmsg=errmsg,
valid=valid,
ends_with_scomment=validandstate==scomment,
oneline="\n"notintextandsemicolons==0,
oneline_with_semicolon= ("\n"notintextandsemicolons==1
andlast_significant_char==';'),
empty=last_significant_char==None,
terminated_badly=last_significant_charnotin {";", "}", None},
get_text=get_text,
semicolons=semicolons
)
defis_valid_substitute(reference_code, student_code):
is_inline=not ("\n"inreference_code)
stuparse=java_parse(student_code)
ifnotstuparse.valid:
return [False, stuparse.errmsg]
ifstuparse.ends_with_scommentandis_inline:
return [False, "// is not allowed"]
refparse=java_parse(reference_code)
ifrefparse.onelineorrefparse.oneline_with_semicolon:
if"\n"instudent_code:
return [False, "newlines are not allowed"]
# if refparse.oneline and stuparse.semicolons > 0:
# return [False, "; is not allowed"]
#if refparse.oneline_with_semicolon and not stuparse.oneline_with_semicolon:
# return [False, "must have exactly one semicolon, at the end"]
ifstuparse.emptyandnotrefparse.empty:
return [False, "must not be empty"]
# if stuparse.terminated_badly and not refparse.terminated_badly:
# return [False, "must end with a semicolon (;) or a {block}"]
return [True]
defrun_tests():
tests= [
("\\u004eow testing. Gives 5 backslashes: \\\\\\u005c\\\\."+
" Will not convert: \\\\u0066, \\u0088. New\\uu000aline, "+
"line\\uuu000dfeed. Ta d\u0061\u0021"),
"a single line",
"a single line with newline at end\n",
"a single line with cr at end\r",
"a single line with tab at end\t",
"a single line with semicolon at end;",
"a single line with semicolon and tab at end;\t",
"a single line with semicolon and newline at end;\n",
"two semicolons;;",
"quoted semicolon \";\"",
"single-quoted semicolon ';'",
"commented semicolon /*;*/",
"inline-commented semicolon //;",
"semicolon followed by comments; /* blah; */ // ",
"semicolon followed by quotes; 'yeah'",
"good braces {}{}{{{}}}",
"wrong kind \u000a of braces {]",
"wrong kind of braces {(})",
"angle brackets arent checked --- since they are operators <>",
"too many {{{{s",
"balanced but unordered }{",
"too many }}}}s",
("/* multi-line comment \u000a ends"+
" here \\u002a/ while (stuff) {do things;}"),
"/* this // is \n a valid comment \"'*/",
"a very short comment; /**/",
"a very short comment /\\u002a\\u002a/",
"a quote \"containing \n a newline\"",
"a quote '\n' with a newline",
"a quote \"\\\\\" with 2 bses",
"a quote \"\\\\\\\" with 3 bses",
"unmatched \"!",
"unmatched '!",
"empty quotes '' \"\" ... the next test is an empty string",
"",
"3 windows newlines\r\n\r\n\r\n",
"carriage\u000dreturn",
"here/*space*/inserted",
"here/*newline\n*/inserted",
"here//newline\ninserted",
"foo",
"foo;\nbar;",
"foo;\nbar//;",
]
r= []
fortestintests:
r.append("\n\n")
result=java_parse(test)
r.append("<br/>Test<pre>"+test+"</pre> yields flags ")
fork, vinresult.__dict__.items():
ifvisTrue:
r.append("["+k+"] ")
gt=result.get_text
ifgt() ==test:
r.append("<br/>")
else:
r.append("and returns changed text:<pre>"+gt()+"</pre>")
ifnotresult.valid:
r.append("and error message:<br/>"+result.errmsg+"<br/>")
ifgt(keep_comments=True) !=gt():
r.append("Stripped text: <pre>"+gt(keep_comments=True) +"</pre><br/>")
return''.join(r)
defrun_tabify_tests():
r= []
tests= ["forloop {\n ifstatement { \n body1; \nbody2;\n}\n}",
"forloop \n{\n ifstatement \n{\n body1; \nbody2;\n}\n}",
"if () {\n stuff \n } else { \n stuff \n}",
"if () \n{\n stuff \n }\nelse\n{\n stuff\n }",
"int[][] x = new int[][]{\n{1, 2},\n,\n{1, 2,\n3\n}\n}",
"((\nshould not indent two levels\n))",
("for (){ // some comment blah \n // comment \n stuff /* multi\n"+
"line*/ \n} // endish")
]
fortestintests:
result=java_parse(test)
with_comments=result.get_text(tabify=True, keep_comments=True)
no_comments=result.get_text(tabify=True, keep_comments=False)
r.append("\n\n<br>")
r.append("<br/>Test<pre>"+test+"</pre>")
r.append("<br/>Tabified:<pre>"+with_comments+"</pre>")
ifwith_comments!=no_comments:
r.append("<br/>Tabified, no comments:<pre>"+no_comments+"</pre>")
return''.join(r)