-
Notifications
You must be signed in to change notification settings - Fork 317
/
XtendValidator.java
2247 lines (2066 loc) · 96.2 KB
/
XtendValidator.java
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2011, 2018 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtend.core.validation;
import static com.google.common.collect.Iterables.*;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Lists.*;
import static com.google.common.collect.Lists.transform;
import static org.eclipse.xtend.core.validation.IssueCodes.*;
import static org.eclipse.xtend.core.xtend.XtendPackage.Literals.*;
import static org.eclipse.xtext.util.JavaVersion.*;
import static org.eclipse.xtext.util.Strings.*;
import static org.eclipse.xtext.util.Strings.isEmpty;
import static org.eclipse.xtext.xbase.XbasePackage.Literals.*;
import static org.eclipse.xtext.xbase.validation.IssueCodes.*;
import java.lang.annotation.ElementType;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.xtend.core.jvmmodel.DispatchHelper;
import org.eclipse.xtend.core.jvmmodel.IXtendJvmAssociations;
import org.eclipse.xtend.core.richstring.RichStringProcessor;
import org.eclipse.xtend.core.typesystem.LocalClassAwareTypeNames;
import org.eclipse.xtend.core.xtend.AnonymousClass;
import org.eclipse.xtend.core.xtend.RichString;
import org.eclipse.xtend.core.xtend.RichStringElseIf;
import org.eclipse.xtend.core.xtend.RichStringForLoop;
import org.eclipse.xtend.core.xtend.RichStringIf;
import org.eclipse.xtend.core.xtend.XtendAnnotationTarget;
import org.eclipse.xtend.core.xtend.XtendAnnotationType;
import org.eclipse.xtend.core.xtend.XtendClass;
import org.eclipse.xtend.core.xtend.XtendConstructor;
import org.eclipse.xtend.core.xtend.XtendEnum;
import org.eclipse.xtend.core.xtend.XtendExecutable;
import org.eclipse.xtend.core.xtend.XtendField;
import org.eclipse.xtend.core.xtend.XtendFile;
import org.eclipse.xtend.core.xtend.XtendFormalParameter;
import org.eclipse.xtend.core.xtend.XtendFunction;
import org.eclipse.xtend.core.xtend.XtendInterface;
import org.eclipse.xtend.core.xtend.XtendMember;
import org.eclipse.xtend.core.xtend.XtendPackage;
import org.eclipse.xtend.core.xtend.XtendParameter;
import org.eclipse.xtend.core.xtend.XtendTypeDeclaration;
import org.eclipse.xtend.core.xtend.XtendVariableDeclaration;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.common.types.JvmAnnotationTarget;
import org.eclipse.xtext.common.types.JvmAnnotationType;
import org.eclipse.xtext.common.types.JvmConstructor;
import org.eclipse.xtext.common.types.JvmDeclaredType;
import org.eclipse.xtext.common.types.JvmExecutable;
import org.eclipse.xtext.common.types.JvmFeature;
import org.eclipse.xtext.common.types.JvmField;
import org.eclipse.xtext.common.types.JvmFormalParameter;
import org.eclipse.xtext.common.types.JvmGenericType;
import org.eclipse.xtext.common.types.JvmIdentifiableElement;
import org.eclipse.xtext.common.types.JvmOperation;
import org.eclipse.xtext.common.types.JvmParameterizedTypeReference;
import org.eclipse.xtext.common.types.JvmPrimitiveType;
import org.eclipse.xtext.common.types.JvmSpecializedTypeReference;
import org.eclipse.xtext.common.types.JvmType;
import org.eclipse.xtext.common.types.JvmTypeParameter;
import org.eclipse.xtext.common.types.JvmTypeReference;
import org.eclipse.xtext.common.types.JvmVisibility;
import org.eclipse.xtext.common.types.JvmWildcardTypeReference;
import org.eclipse.xtext.common.types.TypesPackage;
import org.eclipse.xtext.common.types.util.AnnotationLookup;
import org.eclipse.xtext.common.types.util.DeprecationUtil;
import org.eclipse.xtext.common.types.util.TypeReferences;
import org.eclipse.xtext.diagnostics.Severity;
import org.eclipse.xtext.documentation.IEObjectDocumentationProvider;
import org.eclipse.xtext.documentation.IEObjectDocumentationProviderExtension;
import org.eclipse.xtext.documentation.IJavaDocTypeReferenceProvider;
import org.eclipse.xtext.naming.IQualifiedNameConverter;
import org.eclipse.xtext.naming.QualifiedName;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.scoping.IScope;
import org.eclipse.xtext.scoping.IScopeProvider;
import org.eclipse.xtext.util.JavaVersion;
import org.eclipse.xtext.util.ReplaceRegion;
import org.eclipse.xtext.validation.Check;
import org.eclipse.xtext.validation.ComposedChecks;
import org.eclipse.xtext.validation.ValidationMessageAcceptor;
import org.eclipse.xtext.xbase.XAssignment;
import org.eclipse.xtext.xbase.XBlockExpression;
import org.eclipse.xtext.xbase.XCatchClause;
import org.eclipse.xtext.xbase.XClosure;
import org.eclipse.xtext.xbase.XExpression;
import org.eclipse.xtext.xbase.XFeatureCall;
import org.eclipse.xtext.xbase.XIfExpression;
import org.eclipse.xtext.xbase.XReturnExpression;
import org.eclipse.xtext.xbase.XbasePackage;
import org.eclipse.xtext.xbase.annotations.typing.XAnnotationUtil;
import org.eclipse.xtext.xbase.annotations.validation.XbaseWithAnnotationsValidator;
import org.eclipse.xtext.xbase.annotations.xAnnotations.XAnnotation;
import org.eclipse.xtext.xbase.annotations.xAnnotations.XAnnotationsPackage;
import org.eclipse.xtext.xbase.compiler.GeneratorConfig;
import org.eclipse.xtext.xbase.compiler.IGeneratorConfigProvider;
import org.eclipse.xtext.xbase.compiler.JavaKeywords;
import org.eclipse.xtext.xbase.jvmmodel.IJvmModelAssociations;
import org.eclipse.xtext.xbase.jvmmodel.ILogicalContainerProvider;
import org.eclipse.xtext.xbase.jvmmodel.JvmTypeExtensions;
import org.eclipse.xtext.xbase.lib.util.ToStringBuilder;
import org.eclipse.xtext.xbase.scoping.batch.IFeatureNames;
import org.eclipse.xtext.xbase.scoping.featurecalls.OperatorMapping;
import org.eclipse.xtext.xbase.typesystem.IBatchTypeResolver;
import org.eclipse.xtext.xbase.typesystem.IResolvedTypes;
import org.eclipse.xtext.xbase.typesystem.override.ConflictingDefaultOperation;
import org.eclipse.xtext.xbase.typesystem.override.IOverrideCheckResult.OverrideCheckDetails;
import org.eclipse.xtext.xbase.typesystem.override.IResolvedConstructor;
import org.eclipse.xtext.xbase.typesystem.override.IResolvedExecutable;
import org.eclipse.xtext.xbase.typesystem.override.IResolvedOperation;
import org.eclipse.xtext.xbase.typesystem.override.OverrideHelper;
import org.eclipse.xtext.xbase.typesystem.override.ResolvedFeatures;
import org.eclipse.xtext.xbase.typesystem.references.ITypeReferenceOwner;
import org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference;
import org.eclipse.xtext.xbase.typesystem.references.StandardTypeReferenceOwner;
import org.eclipse.xtext.xbase.typesystem.util.ContextualVisibilityHelper;
import org.eclipse.xtext.xbase.typesystem.util.IVisibilityHelper;
import org.eclipse.xtext.xbase.typesystem.util.RecursionGuard;
import org.eclipse.xtext.xbase.validation.ImplicitReturnFinder;
import org.eclipse.xtext.xbase.validation.ImplicitReturnFinder.Acceptor;
import org.eclipse.xtext.xbase.validation.ProxyAwareUIStrings;
import org.eclipse.xtext.xbase.validation.UIStrings;
import org.eclipse.xtext.xtype.XComputedTypeReference;
import org.eclipse.xtext.xtype.XImportDeclaration;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
/**
* @author Jan Koehnlein - Initial contribution and API
* @author Sebastian Zarnekow
* @author Sven Efftinge
* @author Holger Schill
* @author Stephane Galland
*/
@ComposedChecks(validators = { AnnotationValidation.class })
public class XtendValidator extends XbaseWithAnnotationsValidator {
@Inject
private RichStringProcessor richStringProcessor;
@Inject
private IXtendJvmAssociations associations;
@Inject
private OverrideHelper overrideHelper;
@Inject
private DispatchHelper dispatchHelper;
@Inject
private XAnnotationUtil annotationUtil;
@Inject
private JavaKeywords javaUtils;
@Inject
private UIStrings uiStrings;
@Inject
private ILogicalContainerProvider containerProvider;
@Inject
private JvmTypeExtensions typeExtensions;
@Inject
private IJvmModelAssociations jvmModelAssociations;
@Inject
private IVisibilityHelper visibilityHelper;
@Inject
private IJavaDocTypeReferenceProvider javaDocTypeReferenceProvider;
@Inject
private IScopeProvider scopeProvider;
@Inject
private IEObjectDocumentationProvider documentationProvider;
@Inject
private IQualifiedNameConverter qualifiedNameConverter;
@Inject
private OperatorMapping operatorMapping;
@Inject
private ImplicitReturnFinder implicitReturnFinder;
@Inject
private LocalClassAwareTypeNames localClassAwareTypeNames;
@Inject
private IBatchTypeResolver batchTypeResolver;
@Inject
private ProxyAwareUIStrings proxyAwareUIStrings;
@Inject
private AnnotationLookup annotationLookup;
@Inject
private IGeneratorConfigProvider generatorConfigProvider;
protected final Set<String> visibilityModifers = ImmutableSet.of("public", "private", "protected", "package");
protected final Set<String> junitAnnotations = ImmutableSet.of(
// JUnit4 annotations
"org.junit.Test",
"org.junit.Before",
"org.junit.After",
"org.junit.BeforeClass",
"org.junit.AfterClass",
// JUnit5 annotations
"org.junit.jupiter.api.Test",
"org.junit.jupiter.api.BeforeEach",
"org.junit.jupiter.api.AfterEach",
"org.junit.jupiter.api.BeforeAll",
"org.junit.jupiter.api.AfterAll"
);
protected final Multimap<Class<?>, ElementType> targetInfos;
{
ImmutableMultimap.Builder<Class<?>, ElementType> result = ImmutableMultimap.builder();
result.put(XtendClass.class, ElementType.TYPE);
result.put(XtendInterface.class, ElementType.TYPE);
result.put(XtendEnum.class, ElementType.TYPE);
result.putAll(XtendAnnotationType.class, ElementType.ANNOTATION_TYPE, ElementType.TYPE);
result.put(XtendField.class, ElementType.FIELD);
result.put(XtendFunction.class, ElementType.METHOD);
result.put(XtendParameter.class, ElementType.PARAMETER);
targetInfos = result.build();
}
@Override
protected List<EPackage> getEPackages() {
List<EPackage> ePackages = newArrayList(super.getEPackages());
ePackages.add(XtendPackage.eINSTANCE);
return ePackages;
}
protected GeneratorConfig getGeneratorConfig(EObject element) {
GeneratorConfig result = (GeneratorConfig) getContext().get(GeneratorConfig.class);
if (result == null) {
result = generatorConfigProvider.get(element);
getContext().put(GeneratorConfig.class, result);
if (result.getJavaSourceVersion().isAtLeast(JAVA8)) {
methodInInterfaceModifierValidator = new ModifierValidator(
newArrayList("public", "abstract", "static", "def", "override"), this);
} else {
methodInInterfaceModifierValidator = new ModifierValidator(
newArrayList("public", "abstract", "def", "override"), this);
}
}
return result;
}
protected boolean hasAnnotation(XtendAnnotationTarget source, Class<?> class1) {
for (XAnnotation anno : source.getAnnotations()) {
if (anno != null && anno.getAnnotationType() != null && class1.getName().equals(anno.getAnnotationType().getIdentifier()))
return true;
}
return false;
}
@Check
public void checkValidExtension(XtendField field) {
if (field.isExtension()) {
JvmField jvmField = associations.getJvmField(field);
if (jvmField != null) {
checkValidExtensionType(jvmField, field, XtendPackage.Literals.XTEND_FIELD__TYPE);
}
}
}
@Check
public void checkNonRawTypeInferred(XtendField field) {
if (field.getType() == null) {
JvmField jvmField = associations.getJvmField(field);
// field could have been removed by AA, thus the resource is possibly null
if (jvmField != null && jvmField.eResource() != null) {
JvmTypeReference fieldType = jvmField.getType();
validateInferredType(fieldType, field, "The inferred field type ", XTEND_FIELD__NAME);
}
}
}
@Check
public void checkNonRawTypeInferred(XtendFunction function) {
if (function.getReturnType() == null) {
JvmOperation operation = associations.getDirectlyInferredOperation(function);
// operation could have been removed by AA, thus the resource is possibly null
if (operation != null && operation.eResource() != null) {
JvmTypeReference returnType = operation.getReturnType();
validateInferredType(returnType, function, "The inferred return type ", XTEND_FUNCTION__NAME);
}
}
}
@Check
public void checkJUnitMethodReturnType(XtendFunction function) {
JvmOperation operation = associations.getDirectlyInferredOperation(function);
/*
* Active annotations could also change the return type.
* Checking that the JvmOperation really has a JUnit annotation.
*/
if(hasJUnitAnnotation(operation)) {
LightweightTypeReference actualType = determineReturnType(operation);
if(actualType !=null && !actualType.isUnknown() && !actualType.isPrimitiveVoid()) {
String message = String.format("JUnit method %s() must be void but is %s.", function.getName(), actualType.getHumanReadableName());
EAttribute location = XTEND_FUNCTION__NAME;
error(message, function, location, INVALID_RETURN_TYPE_IN_CASE_OF_JUNIT_ANNOTATION);
}
}
}
private LightweightTypeReference determineReturnType(JvmOperation operation) {
// operation could have been removed by AA, thus the resource is possibly null
if(operation != null && operation.eResource() != null) {
return batchTypeResolver.resolveTypes(operation).getActualType(operation);
}
return null;
}
private boolean hasJUnitAnnotation(JvmOperation operation) {
return !annotationUtil.findAnnotations(junitAnnotations, operation).isEmpty();
}
protected void validateInferredType(JvmTypeReference inferredType, XtendMember member, String messagePrefix,
EAttribute location) {
if (inferredType != null) {
TreeIterator<EObject> iterator = EcoreUtil2.eAll(inferredType);
while(iterator.hasNext()) {
EObject next = iterator.next();
if (next instanceof JvmParameterizedTypeReference) {
JvmParameterizedTypeReference candidate = (JvmParameterizedTypeReference) next;
JvmType type = candidate.getType();
if (type instanceof JvmGenericType && !((JvmGenericType) type).getTypeParameters().isEmpty()) {
if (candidate.getArguments().isEmpty()) {
StringBuilder message = new StringBuilder(messagePrefix);
message = proxyAwareUIStrings.visit(inferredType, message);
if (message != null) {
message.append(" uses the raw type ");
message.append(type.getSimpleName());
message.append(". References to generic type ");
message = proxyAwareUIStrings.appendTypeSignature(type, message);
message.append(" should be parameterized");
warning(message.toString(), member, location, org.eclipse.xtext.xbase.validation.IssueCodes.RAW_TYPE);
}
return;
}
}
} else if (next instanceof XComputedTypeReference) {
validateInferredType(((XComputedTypeReference) next).getEquivalent(), member, messagePrefix, location);
iterator.prune();
}
}
}
}
@Check
public void checkValidExtension(XtendFormalParameter parameter) {
// catch clauses validate their types against java.lang.Throwable
if (parameter.isExtension() && !(parameter.eContainer() instanceof XCatchClause))
checkValidExtensionType(parameter, parameter, TypesPackage.Literals.JVM_FORMAL_PARAMETER__PARAMETER_TYPE);
}
@Check
public void checkValidExtension(XtendVariableDeclaration variableDeclaration) {
if (variableDeclaration.isExtension())
checkValidExtensionType(variableDeclaration, variableDeclaration, XbasePackage.Literals.XVARIABLE_DECLARATION__NAME);
}
@Check
public void checkValidExtension(XtendParameter parameter) {
if (parameter.isExtension()) {
JvmFormalParameter jvmParameter = associations.getJvmParameter(parameter);
if (jvmParameter != null)
checkValidExtensionType(jvmParameter, parameter, XtendPackage.Literals.XTEND_PARAMETER__PARAMETER_TYPE);
}
}
protected void checkValidExtensionType(JvmIdentifiableElement identifiable, EObject source, EStructuralFeature feature) {
LightweightTypeReference type = getActualType(identifiable);
if (type != null && type.isPrimitive()) {
error(String.format("The primitive type %s is not a valid extension", type.getHumanReadableName()), source, feature, INVALID_EXTENSION_TYPE);
}
}
@Check
public void checkAnnotationTarget(XAnnotation annotation) {
JvmType annotationType = annotation.getAnnotationType();
if (annotationType == null || annotationType.eIsProxy() || !(annotationType instanceof JvmAnnotationType)) {
return;
}
Set<ElementType> targets = annotationUtil.getAnnotationTargets((JvmAnnotationType) annotationType);
if (targets.isEmpty())
return;
final EObject eContainer = getContainingAnnotationTarget(annotation);
Class<? extends EObject> clazz = eContainer.getClass();
if (eContainer instanceof XtendField && eContainer.eContainer() instanceof XtendAnnotationType) {
clazz = XtendFunction.class;
}
for (Entry<Class<?>, Collection<ElementType>> mapping : targetInfos.asMap().entrySet()) {
if (mapping.getKey().isAssignableFrom(clazz)) {
targets.retainAll(mapping.getValue());
if (targets.isEmpty()) {
error("The annotation @" + annotation.getAnnotationType().getSimpleName()
+ " is disallowed for this location.", annotation, null, INSIGNIFICANT_INDEX,
ANNOTATION_WRONG_TARGET);
}
}
}
}
@Check
public void checkMultipleAnnotations(final XtendAnnotationTarget annotationTarget) {
if (annotationTarget.getAnnotations().size() <= 1 || !isRelevantAnnotationTarget(annotationTarget)) {
return;
}
ImmutableListMultimap<String, XAnnotation> groupByIdentifier = Multimaps.index(annotationTarget.getAnnotations(),
new Function<XAnnotation, String>() {
@Override
public String apply(XAnnotation input) {
return input.getAnnotationType().getIdentifier();
}
});
for (String qName : groupByIdentifier.keySet()) {
ImmutableList<XAnnotation> sameType = groupByIdentifier.get(qName);
if (sameType.size() > 1) {
JvmType type = sameType.get(0).getAnnotationType();
if (type instanceof JvmAnnotationType && !type.eIsProxy()
&& !annotationLookup.isRepeatable((JvmAnnotationType) type)) {
for (XAnnotation xAnnotation : sameType) {
error("Multiple annotations of non-repeatable type @"
+ xAnnotation.getAnnotationType().getSimpleName()
+ ". Only annotation types marked @Repeatable can be used multiple times at one target.",
xAnnotation, XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE, INSIGNIFICANT_INDEX, ANNOTATION_MULTIPLE);
}
}
}
}
}
protected boolean isRelevantAnnotationTarget(final XtendAnnotationTarget annotationTarget) {
return any(targetInfos.keySet(), new Predicate<Class<?>>() {
@Override
public boolean apply(Class<?> input) {
return input.isInstance(annotationTarget);
}
});
}
protected EObject getContainingAnnotationTarget(XAnnotation annotation) {
final EObject eContainer = annotation.eContainer();
// skip synthetic container
if (eContainer.eClass() == XtendPackage.Literals.XTEND_MEMBER || eContainer.eClass() == XtendPackage.Literals.XTEND_TYPE_DECLARATION) {
return eContainer.eContainer();
}
return eContainer;
}
@Check
public void checkXtendFieldNotPrimitiveVoid(XtendField field) {
JvmTypeReference declaredFieldType = field.getType();
if (isPrimitiveVoid(declaredFieldType)) {
error("void is an invalid type for the field " + field.getName(),
field.getType(), null, INVALID_USE_OF_TYPE);
}
}
@Check
public void checkNoTypeNameShadowing(XtendTypeDeclaration type) {
String name = type.getName();
if (name != null && name.length() > 0) {
XtendTypeDeclaration outer = EcoreUtil2.getContainerOfType(type.eContainer(), XtendTypeDeclaration.class);
while(outer != null) {
if (name.equals(outer.getName())) {
acceptError("The nested type " + name + " cannot hide an enclosing type",
type, XtendPackage.Literals.XTEND_TYPE_DECLARATION__NAME, INSIGNIFICANT_INDEX, INVALID_MEMBER_NAME);
return;
}
outer = EcoreUtil2.getContainerOfType(outer.eContainer(), XtendTypeDeclaration.class);
}
}
}
@Check
public void checkMemberNamesAreUnique(XtendTypeDeclaration xtendType) {
final Multimap<String, XtendField> name2field = HashMultimap.create();
final Multimap<String, XtendTypeDeclaration> name2type = HashMultimap.create();
final Multimap<JvmType, XtendField> type2extension = HashMultimap.create();
for (XtendMember member : xtendType.getMembers()) {
if (member instanceof XtendField) {
XtendField field = (XtendField) member;
if (isEmpty(field.getName())) {
if (field.isExtension()) {
JvmTypeReference typeReference = field.getType();
if (typeReference != null) {
JvmType type = typeReference.getType();
if (type != null)
type2extension.put(type, field);
}
}
} else {
name2field.put(field.getName(), field);
}
} else if (member instanceof XtendTypeDeclaration) {
String name = ((XtendTypeDeclaration) member).getName();
if (name != null && name.length() > 0) {
name2type.put(name, (XtendTypeDeclaration) member);
}
}
}
for(String name: name2field.keySet()) {
Collection<XtendField> fields = name2field.get(name);
if(fields.size() >1) {
for(XtendField field: fields)
error("Duplicate field " + name, field, XtendPackage.Literals.XTEND_FIELD__NAME, DUPLICATE_FIELD);
}
}
for(String name: name2type.keySet()) {
Collection<XtendTypeDeclaration> types = name2type.get(name);
if(types.size() >1) {
for(XtendTypeDeclaration type: types)
error("Duplicate nested type " + name, type, XtendPackage.Literals.XTEND_TYPE_DECLARATION__NAME, DUPLICATE_TYPE_NAME);
}
}
for(JvmType type: type2extension.keySet()) {
Collection<XtendField> fields = type2extension.get(type);
if(fields.size() >1) {
for(XtendField field: fields)
error("Duplicate extension with same type", field, XTEND_FIELD__TYPE, DUPLICATE_FIELD);
}
}
}
@Check
public void checkXtendParameterNotPrimitiveVoid(XtendParameter param) {
if (isPrimitiveVoid(param.getParameterType())) {
XtendFunction function = (XtendFunction) (param.eContainer() instanceof XtendFunction ? param.eContainer()
: null);
if (function != null)
error("void is an invalid type for the parameter " + param.getName() + " of the method "
+ function.getName(), param.getParameterType(), null, INVALID_USE_OF_TYPE);
else
error("void is an invalid type for the parameter " + param.getName(), param.getParameterType(), null,
INVALID_USE_OF_TYPE);
}
}
@Check
public void checkVarArgIsNotExtension(XtendParameter param) {
if (param.isVarArg() && param.isExtension()) {
error("A vararg may not be an extension.", param, XTEND_PARAMETER__EXTENSION, INVALID_USE_OF_VAR_ARG);
}
}
@Check
public void checkVarArgComesLast(XtendParameter param) {
if (param.isVarArg()) {
@SuppressWarnings("unchecked")
List<XtendParameter> params = (List<XtendParameter>) param.eContainer().eGet(param.eContainingFeature());
if (param != Iterables.getLast(params)) {
error("A vararg must be the last parameter.", param, XTEND_PARAMETER__VAR_ARG, INVALID_USE_OF_VAR_ARG);
}
}
}
@Check
public void checkClassPath(XtendFile xtendFile) {
TypeReferences typeReferences = getServices().getTypeReferences();
final JvmGenericType listType = (JvmGenericType) typeReferences.findDeclaredType(List.class, xtendFile);
if (listType == null || listType.getTypeParameters().isEmpty()) {
error("Couldn't find a JDK 1.5 or higher on the project's classpath.", xtendFile, XTEND_FILE__PACKAGE,
IssueCodes.JDK_NOT_ON_CLASSPATH);
} else if (typeReferences.findDeclaredType(ToStringBuilder.class, xtendFile) == null) {
error("Couldn't find the mandatory library 'org.eclipse.xtext.xbase.lib' 2.8.0 or higher on the project's classpath.",
xtendFile, XTEND_FILE__PACKAGE, IssueCodes.XBASE_LIB_NOT_ON_CLASSPATH);
}
}
@Check
public void checkWhitespaceInRichStrings(RichString richString) {
// don't check the indentation of nested rich strings in
// IF and FOR individually
if (richString.eContainer() instanceof RichStringIf) {
RichStringIf container = (RichStringIf) richString.eContainer();
if (container.getThen() == richString || container.getElse() == richString)
return;
}
if (richString.eContainer() instanceof RichStringElseIf) {
RichStringElseIf container = (RichStringElseIf) richString.eContainer();
if (container.getThen() == richString)
return;
}
if (richString.eContainer() instanceof RichStringForLoop) {
RichStringForLoop container = (RichStringForLoop) richString.eContainer();
if (container.getEachExpression() == richString)
return;
}
doCheckWhitespaceIn(richString);
}
protected void doCheckWhitespaceIn(RichString richString) {
ValidatingRichStringAcceptor helper = new ValidatingRichStringAcceptor(this);
richStringProcessor.process(richString, helper, helper);
}
@Check
public void checkSuperTypes(XtendClass xtendClass) {
JvmTypeReference superClass = xtendClass.getExtends();
if (superClass != null && superClass.getType() != null) {
if (!(superClass.getType() instanceof JvmGenericType)
|| ((JvmGenericType) superClass.getType()).isInterface()) {
error("Superclass must be a class", XTEND_CLASS__EXTENDS, CLASS_EXPECTED);
} else {
if (((JvmGenericType) superClass.getType()).isFinal()) {
error("Attempt to override final class", XTEND_CLASS__EXTENDS, OVERRIDDEN_FINAL);
}
checkWildcardSupertype(xtendClass, superClass, XTEND_CLASS__EXTENDS, INSIGNIFICANT_INDEX);
}
}
for (int i = 0; i < xtendClass.getImplements().size(); ++i) {
JvmTypeReference implementedType = xtendClass.getImplements().get(i);
if (!isInterface(implementedType.getType()) && !isAnnotation(implementedType.getType())) {
error("Implemented interface must be an interface", XTEND_CLASS__IMPLEMENTS, i, INTERFACE_EXPECTED);
}
checkWildcardSupertype(xtendClass, implementedType, XTEND_CLASS__IMPLEMENTS, i);
}
JvmGenericType inferredType = associations.getInferredType(xtendClass);
if (inferredType != null && hasCycleInHierarchy(inferredType, Sets.<JvmGenericType> newHashSet())) {
error("The inheritance hierarchy of " + notNull(xtendClass.getName()) + " contains cycles",
XTEND_TYPE_DECLARATION__NAME, CYCLIC_INHERITANCE);
}
}
@Check
public void checkSuperTypes(XtendInterface xtendInterface) {
for (int i = 0; i < xtendInterface.getExtends().size(); ++i) {
JvmTypeReference extendedType = xtendInterface.getExtends().get(i);
if (!isInterface(extendedType.getType()) && !isAnnotation(extendedType.getType())) {
error("Extended interface must be an interface", XTEND_INTERFACE__EXTENDS, i, INTERFACE_EXPECTED);
}
checkWildcardSupertype(xtendInterface, extendedType, XTEND_INTERFACE__EXTENDS, i);
}
JvmGenericType inferredType = associations.getInferredType(xtendInterface);
if(inferredType != null && hasCycleInHierarchy(inferredType, Sets.<JvmGenericType> newHashSet())) {
error("The inheritance hierarchy of " + notNull(xtendInterface.getName()) + " contains cycles",
XTEND_TYPE_DECLARATION__NAME, CYCLIC_INHERITANCE);
}
}
protected boolean isAnnotation(JvmType jvmType) {
return jvmType instanceof JvmAnnotationType;
}
@Check
public void checkSuperTypes(AnonymousClass anonymousClass) {
JvmGenericType inferredType = associations.getInferredType(anonymousClass);
if (inferredType != null) {
JvmTypeReference superTypeRef = Iterables.getLast(inferredType.getSuperTypes());
JvmType superType = superTypeRef.getType();
if(superType instanceof JvmGenericType && ((JvmGenericType) superType).isFinal())
error("Attempt to override final class", anonymousClass.getConstructorCall(), XCONSTRUCTOR_CALL__CONSTRUCTOR, INSIGNIFICANT_INDEX, OVERRIDDEN_FINAL);
}
}
@Check
public void checkStaticMembers(AnonymousClass anonymousClass) {
for (XtendMember member : anonymousClass.getMembers()) {
if (member.isStatic()) {
if (member instanceof XtendExecutable) {
error("A method of an anonymous class cannot be static.", member, XTEND_MEMBER__MODIFIERS,
INSIGNIFICANT_INDEX, ANONYMOUS_CLASS_STATIC_METHOD);
} else if (member instanceof XtendField) {
JvmField field = (JvmField) jvmModelAssociations.getPrimaryJvmElement(member);
if (!member.isFinal()) {
error("A static field of an anonymous class must be final.", member, XTEND_MEMBER__MODIFIERS,
INSIGNIFICANT_INDEX, ANONYMOUS_CLASS_STATIC_FIELD);
} else if (!field.isConstant()) {
error("A static field of an anonymous class must be initialized with a constant expression.",
member, XTEND_FIELD__INITIAL_VALUE, INSIGNIFICANT_INDEX, ANONYMOUS_CLASS_STATIC_FIELD);
}
}
}
}
}
protected void checkWildcardSupertype(XtendTypeDeclaration xtendType, JvmTypeReference superTypeReference,
EStructuralFeature feature, int index) {
if(isInvalidWildcard(superTypeReference))
error("The type "
+ notNull(xtendType.getName())
+ " cannot extend or implement "
+ superTypeReference.getIdentifier()
+ ". A supertype may not specify any wildcard", feature, index, WILDCARD_IN_SUPERTYPE);
}
protected boolean isInvalidWildcard(JvmTypeReference typeRef) {
if (typeRef instanceof JvmWildcardTypeReference)
return true;
else if (typeRef instanceof JvmParameterizedTypeReference) {
for(JvmTypeReference typeArgument: ((JvmParameterizedTypeReference) typeRef).getArguments()) {
if(typeArgument instanceof JvmWildcardTypeReference)
return true;
}
} else if (typeRef instanceof JvmSpecializedTypeReference) {
return isInvalidWildcard(((JvmSpecializedTypeReference) typeRef).getEquivalent());
}
return false;
}
protected boolean hasCycleInHierarchy(JvmGenericType type, Set<JvmGenericType> processedSuperTypes) {
JvmDeclaredType container = type;
do {
if (processedSuperTypes.contains(container))
return true;
container = container.getDeclaringType();
} while (container != null);
processedSuperTypes.add(type);
for (JvmTypeReference superTypeRef : type.getSuperTypes()) {
if (superTypeRef.getType() instanceof JvmGenericType) {
if (hasCycleInHierarchy((JvmGenericType) superTypeRef.getType(), processedSuperTypes))
return true;
}
}
processedSuperTypes.remove(type);
return false;
}
@Check
public void checkDuplicateAndOverriddenFunctions(XtendTypeDeclaration xtendType) {
final JvmDeclaredType inferredType = associations.getInferredType(xtendType);
if (inferredType instanceof JvmGenericType) {
JavaVersion targetVersion = getGeneratorConfig(xtendType).getJavaSourceVersion();
ResolvedFeatures resolvedFeatures = overrideHelper.getResolvedFeatures(inferredType, targetVersion);
Set<EObject> flaggedOperations = Sets.newHashSet();
doCheckDuplicateExecutables((JvmGenericType) inferredType, resolvedFeatures, flaggedOperations);
doCheckOverriddenMethods(xtendType, (JvmGenericType) inferredType, resolvedFeatures, flaggedOperations);
doCheckFunctionOverrides(resolvedFeatures, flaggedOperations);
}
}
protected void doCheckDuplicateExecutables(JvmGenericType inferredType, final ResolvedFeatures resolvedFeatures, Set<EObject> flaggedOperations) {
List<IResolvedOperation> declaredOperations = resolvedFeatures.getDeclaredOperations();
doCheckDuplicateExecutables(inferredType, declaredOperations, new Function<String, List<IResolvedOperation>>() {
@Override
public List<IResolvedOperation> apply(String erasedSignature) {
return resolvedFeatures.getDeclaredOperations(erasedSignature);
}
}, flaggedOperations);
final List<IResolvedConstructor> declaredConstructors = resolvedFeatures.getDeclaredConstructors();
doCheckDuplicateExecutables(inferredType, declaredConstructors, new Function<String, List<IResolvedConstructor>>() {
@Override
public List<IResolvedConstructor> apply(String erasedSignature) {
if (declaredConstructors.size() == 1) {
if (erasedSignature.equals(declaredConstructors.get(0).getResolvedErasureSignature())) {
return declaredConstructors;
}
return Collections.emptyList();
}
List<IResolvedConstructor> result = Lists.newArrayListWithCapacity(declaredConstructors.size());
for(IResolvedConstructor constructor: declaredConstructors) {
if (erasedSignature.equals(constructor.getResolvedErasureSignature())) {
result.add(constructor);
}
}
return result;
}
}, flaggedOperations);
}
protected <Executable extends IResolvedExecutable> void doCheckDuplicateExecutables(JvmGenericType inferredType,
List<Executable> declaredOperations, Function<String, List<Executable>> bySignature, Set<EObject> flaggedOperations) {
Set<Executable> processed = Sets.newHashSet();
for(Executable declaredExecutable: declaredOperations) {
if (!processed.contains(declaredExecutable)) {
List<Executable> sameErasure = bySignature.apply(declaredExecutable.getResolvedErasureSignature());
if (sameErasure.size() > 1) {
Multimap<String, Executable> perSignature = HashMultimap.create(sameErasure.size(), 2);
outer: for(Executable executable: sameErasure) {
for(LightweightTypeReference parameterType: executable.getResolvedParameterTypes()) {
if (parameterType.isUnknown())
continue outer;
}
perSignature.put(executable.getResolvedSignature(), executable);
}
if (perSignature.size() > 1) {
for(Collection<Executable> sameSignature: perSignature.asMap().values()) {
for(Executable operationWithSameSignature: sameSignature) {
JvmExecutable executable = operationWithSameSignature.getDeclaration();
EObject otherSource = associations.getPrimarySourceElement(executable);
if (flaggedOperations.add(otherSource)) {
if (sameSignature.size() > 1) {
error("Duplicate " + typeLabel(executable) + " " + operationWithSameSignature.getSimpleSignature()
+ " in type " + inferredType.getSimpleName(), otherSource,
nameFeature(otherSource), DUPLICATE_METHOD);
} else {
error("The " + typeLabel(executable) + " " + operationWithSameSignature.getSimpleSignature()
+ " has the same erasure "
+ operationWithSameSignature.getResolvedErasureSignature()
+ " as another " + typeLabel(executable) + " in type " + inferredType.getSimpleName(), otherSource,
nameFeature(otherSource), DUPLICATE_METHOD);
}
}
}
}
}
}
}
}
}
protected String typeLabel(JvmExecutable executable) {
if (executable instanceof JvmOperation)
return "method";
else if(executable instanceof JvmConstructor)
return "constructor";
else
return "?";
}
protected EStructuralFeature nameFeature(EObject member) {
if (member instanceof XtendFunction)
return XTEND_FUNCTION__NAME;
else if(member instanceof XtendConstructor)
return null;
else if(member instanceof XtendField)
return XTEND_FIELD__NAME;
else
return null;
}
protected EStructuralFeature returnTypeFeature(EObject member) {
if (member instanceof XtendFunction)
return XTEND_FUNCTION__RETURN_TYPE;
else if (member instanceof XtendField) // e.g., for an active annotation like @Accessors
return XTEND_FIELD__TYPE;
else
return null;
}
protected void doCheckOverriddenMethods(XtendTypeDeclaration xtendType, JvmGenericType inferredType, ResolvedFeatures resolvedFeatures,
Set<EObject> flaggedOperations) {
List<IResolvedOperation> operationsMissingImplementation = null;
boolean doCheckAbstract = !inferredType.isAbstract();
if (doCheckAbstract) {
operationsMissingImplementation = Lists.newArrayList();
}
IVisibilityHelper visibilityHelper = new ContextualVisibilityHelper(this.visibilityHelper, resolvedFeatures.getType());
boolean flaggedType = false;
for (IResolvedOperation operation : resolvedFeatures.getAllOperations()) {
JvmDeclaredType operationDeclaringType = operation.getDeclaration().getDeclaringType();
if (operationDeclaringType != inferredType) {
if (operationsMissingImplementation != null && operation.getDeclaration().isAbstract()) {
operationsMissingImplementation.add(operation);
}
if (visibilityHelper.isVisible(operation.getDeclaration())) {
String erasureSignature = operation.getResolvedErasureSignature();
List<IResolvedOperation> declaredOperationsWithSameErasure = resolvedFeatures.getDeclaredOperations(erasureSignature);
for (IResolvedOperation localOperation : declaredOperationsWithSameErasure) {
if (!localOperation.isOverridingOrImplementing(operation.getDeclaration()).isOverridingOrImplementing()) {
EObject source = findPrimarySourceElement(localOperation);
if (operation.getDeclaration().isStatic() && !localOperation.getDeclaration().isStatic()) {
if (!isInterface(operationDeclaringType)) {
if (flaggedOperations.add(source)) {
error("The instance method "
+ localOperation.getSimpleSignature()
+ " cannot override the static method "
+ operation.getSimpleSignature() + " of type "
+ getDeclaratorName(operation.getDeclaration()) + ".",
source, nameFeature(source), DUPLICATE_METHOD);
}
}
} else if (!operation.getDeclaration().isStatic() && localOperation.getDeclaration().isStatic()) {
if (flaggedOperations.add(source)) {
error("The static method "
+ localOperation.getSimpleSignature()
+ " cannot hide the instance method "
+ operation.getSimpleSignature() + " of type "
+ getDeclaratorName(operation.getDeclaration()) + ".",
source, nameFeature(source), DUPLICATE_METHOD);
}
} else if (flaggedOperations.add(source)) {
error("Name clash: The method "
+ localOperation.getSimpleSignature() + " of type "
+ inferredType.getSimpleName()
+ " has the same erasure as "
+ operation.getSimpleSignature() + " of type "
+ getDeclaratorName(operation.getDeclaration()) + " but does not override it.",
source, nameFeature(source), DUPLICATE_METHOD);
}
}
}
if (operation instanceof ConflictingDefaultOperation
&& contributesToConflict(inferredType, (ConflictingDefaultOperation) operation) && !flaggedType) {
IResolvedOperation conflictingOperation = ((ConflictingDefaultOperation) operation).getConflictingOperations()
.get(0);
// Include the declaring class in the issue code in order to give better quick fixes
String[] uris = new String[] {
getDeclaratorName(operation.getDeclaration()) + "|"
+ EcoreUtil.getURI(operation.getDeclaration()).toString(),
getDeclaratorName(conflictingOperation.getDeclaration()) + "|"
+ EcoreUtil.getURI(conflictingOperation.getDeclaration()).toString() };
if (!operation.getDeclaration().isAbstract() && !conflictingOperation.getDeclaration().isAbstract()) {
error("The type " + inferredType.getSimpleName() + " inherits multiple implementations of the method "
+ conflictingOperation.getSimpleSignature() + " from "
+ getDeclaratorName(conflictingOperation.getDeclaration()) + " and "
+ getDeclaratorName(operation.getDeclaration()) + ".", xtendType,
XtendPackage.Literals.XTEND_TYPE_DECLARATION__NAME, CONFLICTING_DEFAULT_METHODS, uris);
} else {
// At least one of the operations is non-abstract
IResolvedOperation abstractOp, nonabstractOp;
if (operation.getDeclaration().isAbstract()) {
abstractOp = operation;
nonabstractOp = conflictingOperation;
} else {
abstractOp = conflictingOperation;
nonabstractOp = operation;
}
error("The non-abstract method " + nonabstractOp.getSimpleSignature() + " inherited from "
+ getDeclaratorName(nonabstractOp.getDeclaration()) + " conflicts with the method "
+ abstractOp.getSimpleSignature() + " inherited from " + getDeclaratorName(abstractOp.getDeclaration())
+ ".", xtendType, XtendPackage.Literals.XTEND_TYPE_DECLARATION__NAME, CONFLICTING_DEFAULT_METHODS,
uris);
}
flaggedType = true;
}
}
}
}
if (operationsMissingImplementation != null && !operationsMissingImplementation.isEmpty() && !flaggedType) {
reportMissingImplementations(xtendType, inferredType, operationsMissingImplementation);
}
}
/**
* Determine whether the given type contributes to the conflict caused by the given default interface implementation.
*/
private boolean contributesToConflict(JvmGenericType rootType, ConflictingDefaultOperation conflictingDefaultOperation) {
Set<JvmDeclaredType> involvedInterfaces = Sets.newHashSet();
involvedInterfaces.add(conflictingDefaultOperation.getDeclaration().getDeclaringType());
for (IResolvedOperation conflictingOperation : conflictingDefaultOperation.getConflictingOperations()) {
involvedInterfaces.add(conflictingOperation.getDeclaration().getDeclaringType());
}
RecursionGuard<JvmDeclaredType> recursionGuard = new RecursionGuard<JvmDeclaredType>();
if (rootType.isInterface()) {
int contributingCount = 0;
for (JvmTypeReference typeRef : rootType.getExtendedInterfaces()) {
JvmType rawType = typeRef.getType();
if (rawType instanceof JvmDeclaredType && contributesToConflict((JvmDeclaredType) rawType, involvedInterfaces, recursionGuard)) {
contributingCount++;
}
}
return contributingCount >= 2;
} else {
return contributesToConflict(rootType, involvedInterfaces, recursionGuard);
}