-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaLang.py
More file actions
738 lines (572 loc) · 17.2 KB
/
Copy pathJavaLang.py
File metadata and controls
738 lines (572 loc) · 17.2 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
#@Jonathan Ke (jak2)
#@9/26/2019
#
#Names groupings and lists of Java syntax and diction
#implements Java grammar rules
#Includes functions for updating JavaGrammar text file with editing functions and grammar prioritization
#algorithms. Functions are called by MochaPythonIDE
#
#lists not completed!!!!!!
from TreeNode import TreeNode
from Token import *
class JavaLang(object):
keywords = tuple("""abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while""".split())
primitives = tuple("""
int boolean double byte
float char short long
""".split())
separators = tuple(".,;{}[]()")
operators = tuple(reversed("""
= > < ! ~ ? :
== <= >= != && || ++ --
+ - * / & | ^ % << >> >>>
+= -= *= /= &= |= ^= %= <<= >>= >>=
""".split()))
keywordsLang = "' | '".join(keywords)
separatorLang = "' | '".join(separators)
operatorsLang = "' | '".join(operators)
primitivesLang = "' | '".join(primitives)
JavaGrammar2 = '''Identifier:
IDENTIFIER
QualifiedIdentifier:
Identifier { . Identifier }
QualifiedIdentifierList:
QualifiedIdentifier { , QualifiedIdentifier }
CompilationUnit:
[[Annotations] package QualifiedIdentifier ;] {ImportDeclaration} {TypeDeclaration}
ImportDeclaration:
import [static] Identifier { . Identifier } [. *] ;
TypeDeclaration:
ClassOrInterfaceDeclaration
;
ClassOrInterfaceDeclaration:
{Modifier} (ClassDeclaration | InterfaceDeclaration)
ClassDeclaration:
NormalClassDeclaration
EnumDeclaration
InterfaceDeclaration:
NormalInterfaceDeclaration
AnnotationTypeDeclaration
NormalClassDeclaration:
class Identifier [TypeParameters] [extends Type] [implements TypeList] ClassBody
EnumDeclaration:
enum Identifier [implements TypeList] EnumBody
NormalInterfaceDeclaration:
interface Identifier [TypeParameters] [extends TypeList] InterfaceBody
AnnotationTypeDeclaration:
@ interface Identifier AnnotationTypeBody
Type:
BasicType { [ ] }
ReferenceType { [ ] }
BasicType:
byte
short
char
int
long
float
double
boolean
ReferenceType:
Identifier [TypeArguments] { . Identifier [TypeArguments] }
TypeArguments:
< TypeArgument { , TypeArgument } >
TypeArgument:
ReferenceType
? [ (extends | super) ReferenceType ]
NonWildcardTypeArguments:
< TypeList >
TypeList:
ReferenceType { , ReferenceType }
TypeArgumentsOrDiamond:
< >
TypeArguments
NonWildcardTypeArgumentsOrDiamond:
< >
NonWildcardTypeArguments
TypeParameters:
< TypeParameter { , TypeParameter } >
TypeParameter:
Identifier [extends Bound]
Bound:
ReferenceType { & ReferenceType }
Modifier:
Annotation
public
protected
private
static
abstract
final
native
synchronized
transient
volatile
strictfp
Annotations:
Annotation {Annotation}
Annotation:
@ QualifiedIdentifier [( [AnnotationElement] )]
AnnotationElement:
ElementValuePairs
ElementValue
ElementValuePairs:
ElementValuePair { , ElementValuePair }
ElementValuePair:
Identifier = ElementValue
ElementValue:
Annotation
Expression1
ElementValueArrayInitializer
ElementValueArrayInitializer:
{ [ElementValues] [,] }
ElementValues:
ElementValue { , ElementValue }
ClassBody:
{ {ClassBodyDeclaration} }
ClassBodyDeclaration:
;
{Modifier} MemberDecl
[static] Block
MemberDecl:
MethodOrFieldDecl
void Identifier VoidMethodDeclaratorRest
Identifier ConstructorDeclaratorRest
GenericMethodOrConstructorDecl
ClassDeclaration
InterfaceDeclaration
MethodOrFieldDecl:
Type Identifier MethodOrFieldRest
MethodOrFieldRest:
FieldDeclaratorsRest ;
MethodDeclaratorRest
FieldDeclaratorsRest:
VariableDeclaratorRest { , VariableDeclarator }
MethodDeclaratorRest:
FormalParameters { [ ] } [throws QualifiedIdentifierList] (Block | ;)
VoidMethodDeclaratorRest:
FormalParameters [throws QualifiedIdentifierList] (Block | ;)
ConstructorDeclaratorRest:
FormalParameters [throws QualifiedIdentifierList] Block
GenericMethodOrConstructorDecl:
TypeParameters GenericMethodOrConstructorRest
GenericMethodOrConstructorRest:
(Type | void) Identifier MethodDeclaratorRest
Identifier ConstructorDeclaratorRest
InterfaceBody:
{ {InterfaceBodyDeclaration} }
InterfaceBodyDeclaration:
;
{Modifier} InterfaceMemberDecl
InterfaceMemberDecl:
InterfaceMethodOrFieldDecl
void Identifier VoidInterfaceMethodDeclaratorRest
InterfaceGenericMethodDecl
ClassDeclaration
InterfaceDeclaration
InterfaceMethodOrFieldDecl:
Type Identifier InterfaceMethodOrFieldRest
InterfaceMethodOrFieldRest:
ConstantDeclaratorsRest ;
InterfaceMethodDeclaratorRest
ConstantDeclaratorsRest:
ConstantDeclaratorRest { , ConstantDeclarator }
ConstantDeclaratorRest:
{ [ ] } = VariableInitializer
ConstantDeclarator:
Identifier ConstantDeclaratorRest
InterfaceMethodDeclaratorRest:
FormalParameters { [ ] } [throws QualifiedIdentifierList] ;
VoidInterfaceMethodDeclaratorRest:
FormalParameters [throws QualifiedIdentifierList] ;
InterfaceGenericMethodDecl:
TypeParameters (Type | void) Identifier InterfaceMethodDeclaratorRest
FormalParameters:
( [FormalParameterDecls] )
FormalParameterDecls:
{VariableModifier} Type FormalParameterDeclsRest
VariableModifier:
final
Annotation
FormalParameterDeclsRest:
VariableDeclaratorId [, FormalParameterDecls]
... VariableDeclaratorId
VariableDeclaratorId:
Identifier { [ ] }
VariableDeclarators:
VariableDeclarator { , VariableDeclarator }
VariableDeclarator:
Identifier [VariableDeclaratorRest]
VariableDeclaratorRest:
{ [ ] } [= VariableInitializer]
VariableInitializer:
ArrayInitializer
Expression
ArrayInitializer:
{ArrayInitializerSub}
ArrayInitializerSub:
{ [ VariableInitializer { , VariableInitializer } [,] ] }
Block:
{ {BlockStatements} }
BlockStatements:
{BlockStatement}
BlockStatement:
LocalVariableDeclarationStatement
ClassOrInterfaceDeclaration
Statement
LocalVariableDeclarationStatement:
{VariableModifier} Type VariableDeclarators ;
Statement:
Block
;
Identifier : Statement
StatementExpression ;
if ParExpression Statement [ElseStatement]
assert Expression [: Expression] ;
switch ParExpression { SwitchBlockStatementGroups }
while ParExpression Statement
do Statement WhileSubStatement ;
for ( ForControl ) Statement
break [Identifier] ;
continue [Identifier] ;
return [Expression] ;
throw Expression ;
synchronized ParExpression Block
try Block (Catches | [Catches] Finally)
try ResourceSpecification Block [Catches] [Finally]
WhileSubStatement:
while ParExpression
ElseStatement:
else Statement
StatementExpression:
Expression
Catches:
CatchClause { CatchClause }
CatchClause:
catch ( {VariableModifier} CatchType Identifier ) Block
CatchType:
QualifiedIdentifier { | QualifiedIdentifier }
Finally:
finally Block
ResourceSpecification:
( Resources [;] )
Resources:
Resource { ; Resource }
Resource:
{VariableModifier} ReferenceType VariableDeclaratorId = Expression
SwitchBlockStatementGroups:
{ SwitchBlockStatementGroup }
SwitchBlockStatementGroup:
SwitchLabels BlockStatements
SwitchLabels:
SwitchLabel { SwitchLabel }
SwitchLabel:
case Expression :
case EnumConstantName :
default :
EnumConstantName:
Identifier
ForControl:
ForVarControl
ForInit ; [Expression] ; [ForUpdate]
ForControlExp:
Expression
ForVarControl:
{VariableModifier} Type VariableDeclaratorId ForVarControlRest
ForVarControlRest:
ForVariableDeclaratorsRest ; [ForControlExp] ; [ForUpdate]
: Expression
ForVariableDeclaratorsRest:
[= VariableInitializer] { , VariableDeclarator }
ForInit:
ForUpdate:
StatementExpression
Expression:
Expression1 [AssignmentOperator Expression1]
AssignmentOperator:
=
+=
-=
*=
/=
&=
|=
^=
%=
<<=
>>=
>>>=
Expression1:
Expression2 [Expression1Rest]
Expression1Rest:
? Expression : Expression1
Expression2:
Expression3 [Expression2Rest]
Expression2Rest:
{ InfixOp Expression3 }
instanceof Type
InfixOp:
||
&&
|
^
&
==
!=
<
>
<=
>=
<<
>>
>>>
+
-
*
/
%
Expression3:
++ Expression3
-- Expression3
PrefixOp Expression3
( (Expression | Type) ) Expression3
Primary {Selector} {PostfixOp}
PrefixOp:
!
~
+
-
PostfixOp:
++
--
Primary:
Literal
ParExpression
Identifier { . Identifier } [IdentifierSuffix]
this [Arguments]
super SuperSuffix
new Creator
NonWildcardTypeArguments (ExplicitGenericInvocationSuffix | this Arguments)
BasicType { [ ] } . class
void . class
Literal:
IntegerLiteral
FloatingPointLiteral
CharacterLiteral
StringLiteral
BooleanLiteral
NullLiteral
ParExpression:
( Expression )
Arguments:
( [ArgumentsSub] )
ArgumentsSub:
Expression { , Expression }
SuperSuffix:
Arguments
. Identifier [Arguments]
ExplicitGenericInvocationSuffix:
super SuperSuffix
Identifier Arguments
Creator:
Type [ Expression ]
NonWildcardTypeArguments CreatedName ClassCreatorRest
[CreatedName] (ClassCreatorRest | ArrayCreatorRest)
CreatedName:
Identifier [TypeArgumentsOrDiamond] { . Identifier [TypeArgumentsOrDiamond] }
ClassCreatorRest:
Arguments [ClassBody]
ArrayCreatorRest:
[ (] { [ ] } ArrayInitializer | Expression ] {[ Expression ]} { [ ] })
IdentifierSuffix:
Arguments
IdentifierSuffixSub
. (class | ExplicitGenericInvocation | this)
. new [NonWildcardTypeArguments] InnerCreator
. super Arguments
IdentifierSuffixSub:
{ [ ] } . class
Expression
ExplicitGenericInvocation:
NonWildcardTypeArguments ExplicitGenericInvocationSuffix
InnerCreator:
Identifier [NonWildcardTypeArgumentsOrDiamond] ClassCreatorRest
Selector:
. Identifier [Arguments]
. ExplicitGenericInvocation
. this
. super SuperSuffix
. new [NonWildcardTypeArguments] InnerCreator
[ Expression ]
EnumBody:
{ [EnumConstants] [,] [EnumBodyDeclarations] }
EnumConstants:
EnumConstant
EnumConstants , EnumConstant
EnumConstant:
[Annotations] Identifier [Arguments] [ClassBody]
EnumBodyDeclarations:
; {ClassBodyDeclaration}
AnnotationTypeBody:
{ [AnnotationTypeElementDeclarations] }
AnnotationTypeElementDeclarations:
AnnotationTypeElementDeclaration
AnnotationTypeElementDeclarations AnnotationTypeElementDeclaration
AnnotationTypeElementDeclaration:
{Modifier} AnnotationTypeElementRest
AnnotationTypeElementRest:
Type Identifier AnnotationMethodOrConstantRest ;
ClassDeclaration
InterfaceDeclaration
EnumDeclaration
AnnotationTypeDeclaration
AnnotationMethodOrConstantRest:
AnnotationMethodRest
ConstantDeclaratorsRest
AnnotationMethodRest:
( ) [[ ]] [default ElementValue]
'''
'''
@staticmethod
#DO NOT USE!!!!!!!!!!!!!!! Will edit JavaGrammar file in horrible ways... DONT TOUCH!
def tagGrammarLinesStart():
javaFile = open('JavaGrammar', 'r')
javaGrammar = javaFile.read().splitlines()
javaFile.close()
for i in range(len(javaGrammar)):
line = javaGrammar[i]
if line != '' and line[0] == ' ': #valid line
line += ' 0'
javaGrammar[i] = line
javaFile = open('JavaGrammar', 'w')
for line in javaGrammar:
javaFile.write(line+'\n')
javaFile.close()
'''
#updates JavaGrammar with analytics from javaTree structure
@staticmethod
def updateGrammar(javaTree):
#get all grammars used in captureGrammars
treeGrammars = dict()
JavaLang.captureGrammars(javaTree, treeGrammars)
#open grammar file
javaFile = open('JavaGrammar', 'r')
javaGrammar = javaFile.read().splitlines()
javaFile.close()
#create dictionary of grammars for searching
ordering, grammarDict = JavaLang.createCurrentGrammarDict(javaGrammar)
#add children grammars in parents, update orderings of grammar
for grammar in treeGrammars:
possGrammars = grammarDict[grammar]
for child in treeGrammars[grammar]:
for struct in possGrammars:
if child == struct[:-1]: #last value in struct is occurence count
struct[-1] = str(int(struct[-1])+1)
break
#cannot add new grammar definitions due
#to limitations in expression parsing :(
#the grammar implemented to parse Java has its limitations sadly...
#merge sort children and set to grammar key
grammarDict[grammar] = JavaLang.mergeSortGrammars(possGrammars)
#rewrite grammar file
file = open('JavaGrammar','w+')
for grammarName in ordering:
file.write(grammarName+'\n')
for struct in grammarDict[grammarName]:
file.write('\t'+' '.join(struct)+'\n')
file.write('\n')
file.close()
#sorts the grammar specifications for a certain grammar structure
#using merge sort algorithm, implemented recursively
@staticmethod
def mergeSortGrammars(L):
if len(L) <= 1:
return L
half = len(L)//2
L1 = JavaLang.mergeSortGrammars(L[:half])
L2 = JavaLang.mergeSortGrammars(L[half:])
out = []
i1 = 0
i2 = 0
while True:
if i1 >= len(L1):
out.extend(L2[i2:])
return out
elif i2 >= len(L2):
out.extend(L1[i1:])
return out
if int(L1[i1][-1]) > int(L2[i2][-1]):
out.append(L1[i1])
i1 += 1
else:
out.append(L2[i2])
i2 += 1
#takes grammar specification and breaks it down into a dictionary
#and ordered list
@staticmethod
def createCurrentGrammarDict(javaGrammar):
#get current state of grammar
currentGrammar = dict() #hash the parent definitions
dictOrder = [] #keep track of their orders though!
parent = None
for line in javaGrammar:
if line != '':
if line[0].isspace():
#is child definition
lineList = line.split() #omit count(the last element)
currentGrammar[parent].append(lineList)
else:
#is a parent definition
currentGrammar[line.strip()] = []
parent = line.strip()
dictOrder.append(parent)
return dictOrder, currentGrammar
#adds grammars found in javaTree to currentDict
@staticmethod
def captureGrammars(javaTree, currentDict):
node, grammar = JavaLang.getGrammarFromNode(javaTree)
if node in currentDict:
currentDict[node].append(grammar)
else:
currentDict[node] = [grammar]
for child in javaTree.children:
if isinstance(child, TreeNode):
JavaLang.captureGrammars(child, currentDict)
#creates grammar-definition tuple from a TreeNode object
@staticmethod
def getGrammarFromNode(node):
name = node.name+':'
children = node.children
grammar = list()
for child in children:
if isinstance(child, TreeNode):
grammar.append(child.name)
elif isinstance(child, Token):
if (isinstance(child, Separator)
or isinstance(child, Keyword)
or isinstance(child, Operator)):
grammar.append(child.string)
elif isinstance(child, Identifier):
grammar.append('Identifier')
elif isinstance(child, Literal):
grammar.append('Literal')
return (name, grammar)
def testGetGrammarFromNode():
node = TreeNode('GenericNode')
node.children = [TreeNode('AnotherGenericNode'), Separator('('), Keyword('public'),
Identifier('MYID'), Literal('"LITTY"'), Operator('+')]
assert(JavaLang.getGrammarFromNode(node)
== ('GenericNode', ('AnotherGenericNode', '(', 'public', 'Identifier', 'Literal', '+')))
#testGetGrammarFromNode()