Java源码示例:org.eclipse.xtext.validation.Check
示例1
/**
* general top-level test: - invalid statements for StaticPolyfillModules. Constraints 140 (restrictions on
* static-polyfilling) IDE-1735
*/
@Check
public void checkVariableStatement(Statement statement) {
EObject con = statement.eContainer();
if (con instanceof Script) { // top-level elements will be checked only.
Script script = (Script) con;
if (!isContainedInStaticPolyfillModule(script)) {
return;
}
// FunctionDeclarations have finer grained check in own validator.
if (statement instanceof FunctionDeclaration)
return;
// it is a static polyfill module
addIssue(getMessageForPOLY_STATIC_POLYFILL_MODULE_ONLY_FILLING_CLASSES(), statement,
POLY_STATIC_POLYFILL_MODULE_ONLY_FILLING_CLASSES);
}
}
示例2
@Check
public void checkOppositeReferenceUsed(Assignment assignment) {
Severity severity = getIssueSeverities(getContext(), getCurrentObject()).getSeverity(BIDIRECTIONAL_REFERENCE);
if (severity == null || severity == Severity.IGNORE) {
// Don't perform any check if the result is ignored
return;
}
EClassifier classifier = GrammarUtil.findCurrentType(assignment);
if (classifier instanceof EClass) {
EStructuralFeature feature = ((EClass) classifier).getEStructuralFeature(assignment.getFeature());
if (feature instanceof EReference) {
EReference reference = (EReference) feature;
if (reference.getEOpposite() != null && !(reference.isContainment() || reference.isContainer())) {
addIssue("The feature '" + assignment.getFeature() + "' is a bidirectional reference."
+ " This may cause problems in the linking process.",
assignment, XtextPackage.eINSTANCE.getAssignment_Feature(), BIDIRECTIONAL_REFERENCE);
}
}
}
}
示例3
/**
* Constraints 3 and 4.2
*/
@Check
public void checkN4TypeDeclaration(N4TypeDeclaration n4TypeDeclaration) {
if (isNotChecked(n4TypeDeclaration)) {
return;
}
// quick exit:
if (Character.isUpperCase(n4TypeDeclaration.getName().charAt(0))) {
return;
}
if (holdsTypeNameNotIndistinguishable(n4TypeDeclaration, "getter/setter", GETTER_SETTER) //
&& holdsTypeNameNotIndistinguishable(n4TypeDeclaration, "access modifier", ACCESS_MODIFIERS) //
&& holdsTypeNameNotIndistinguishable(n4TypeDeclaration, "boolean literal", BOOLEAN_LITERALS) //
&& holdsTypeNameNotIndistinguishable(n4TypeDeclaration, "base type", BASE_TYPES) //
&& holdsTypeNameNotIndistinguishable(n4TypeDeclaration, "keyword",
languageHelper.getECMAKeywords())
&& holdsDoesNotStartWithLowerCaseLetter(n4TypeDeclaration)) {
// error messages are created with in constraint validation
}
}
示例4
/**
* Checks if the value of a given {@link HtmlAttr} is valid. Generates
* errors if the value of a given {@link HtmlAttr} is not supported by
* Graphviz.
*
* @param attr
* The {@link HtmlAttr} of that's attribute value is to check.
*/
@Check
public void checkAttributeValueIsValid(HtmlAttr attr) {
String htmlAttributeName = attr.getName();
// trim the leading and trailing (single or double) quotes if necessary
String htmlAttributeValue = removeQuotes(attr.getValue());
EObject container = attr.eContainer();
if (container instanceof HtmlTag) {
HtmlTag tag = (HtmlTag) container;
String htmlTagName = tag.getName();
String message = getAttributeValueErrorMessage(htmlTagName,
htmlAttributeName, htmlAttributeValue);
if (message != null) {
reportRangeBasedError(HTML_ATTRIBUTE_INVALID_ATTRIBUTE_VALUE,
"The value '" + htmlAttributeValue
+ "' is not a correct " + htmlAttributeName
+ ": " + message,
attr, HtmllabelPackage.Literals.HTML_ATTR__VALUE);
}
}
}
示例5
@Check
public void checkRuleRecursion(XFeatureCall featureCall) {
Rule containingRule = EcoreUtil2.<Rule>getContainerOfType(featureCall, Rule.class);
if (containingRule != null) {
if (featureCall.getFeature() instanceof JvmOperation
&& "fire".equals(featureCall.getConcreteSyntaxFeatureName())
&& featureCall.getFeatureCallArguments().size() == 1) {
XExpression argument = featureCall.getFeatureCallArguments().get(0);
if (argument instanceof XAbstractFeatureCall) {
EObject sourceElem = jvmModelAssociations
.getPrimarySourceElement(((XAbstractFeatureCall) argument).getFeature());
if (sourceElem == containingRule
.getDeviceState()) {
warning("Firing the same device state that triggers the rule \"" + containingRule.getDescription()
+ "\" may lead to endless recursion.", featureCall,
XbasePackage.Literals.XFEATURE_CALL__FEATURE_CALL_ARGUMENTS, 0);
}
}
}
}
}
示例6
@Check
public void checkGeneratedEnumIsValid(EnumLiteralDeclaration decl) {
EnumRule rule = GrammarUtil.containingEnumRule(decl);
if (!(rule.getType().getMetamodel() instanceof GeneratedMetamodel))
return;
if (!(rule.getType().getClassifier() instanceof EEnum))
return;
EEnum eEnum = (EEnum) rule.getType().getClassifier();
List<EnumLiteralDeclaration> declarations = EcoreUtil2.getAllContentsOfType(rule, EnumLiteralDeclaration.class);
if (declarations.size() == eEnum.getELiterals().size())
return;
for (EnumLiteralDeclaration otherDecl : declarations) {
if (decl == otherDecl) {
return;
}
if (otherDecl.getEnumLiteral() == decl.getEnumLiteral()) {
if (!decl.getEnumLiteral().getLiteral().equals(decl.getLiteral().getValue()))
addIssue("Enum literal '" + decl.getEnumLiteral().getName()
+ "' has already been defined with literal '" + decl.getEnumLiteral().getLiteral() + "'.",
decl,
XtextPackage.Literals.ENUM_LITERAL_DECLARATION__ENUM_LITERAL,
DUPLICATE_ENUM_LITERAL);
return;
}
}
}
示例7
/**
* Checks that Category names are unique across the Check Catalog.
*
* @param catalog
* the check catalog
*/
@Check
public void checkCategoryNamesAreUnique(final CheckCatalog catalog) {
Function<Category, QualifiedName> function = new Function<Category, QualifiedName>() {
@Override
public QualifiedName apply(final Category from) {
return QualifiedName.create(from.getName());
}
};
UniquenessJavaValidationHelper<Category> helper = new UniquenessJavaValidationHelper<Category>(function, getMessageAcceptor()) {
@Override
public String getMessage(final Category duplicate) {
return NLS.bind("Duplicate Category name: {0}", duplicate.getName()); //$NON-NLS-1$
}
};
helper.errorOnDuplicates(catalog.getCategories(), locationInFileProvider::getIdentifierFeature, IssueCodes.DUPLICATE_CATEGORY);
}
示例8
@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);
}
}
}
示例9
/**
* Checks that the interface referenced by a fingerprint is defined.
*
* @param context
* export to check
*/
@Check
public void checkFingerprintInterfaceDefined(final Export context) {
if (context.isFingerprint() || context.isResourceFingerprint()) {
ExportModel model = EObjectUtil.eContainer(context, ExportModel.class);
Interface match = null;
for (Interface iface : model.getInterfaces()) {
if (iface.getType().isSuperTypeOf(context.getType())) {
match = iface;
break;
}
}
if (match == null) {
error("No matching interface specification declared", context.isFingerprint() ? ExportPackage.Literals.EXPORT__FINGERPRINT
: ExportPackage.Literals.EXPORT__RESOURCE_FINGERPRINT);
}
}
}
示例10
@Check
public void checkTypeParameterNotUsedInStaticContext(JvmTypeReference ref) {
if(ref.getType() instanceof JvmTypeParameter) {
JvmTypeParameter typeParameter = (JvmTypeParameter) ref.getType();
if (!(typeParameter.getDeclarator() instanceof JvmOperation) || !isTypeParameterOfClosureImpl(ref)) {
EObject currentParent = logicalContainerProvider.getNearestLogicalContainer(ref);
while(currentParent != null) {
if(currentParent == typeParameter.eContainer())
return;
else if(isStaticContext(currentParent))
error("Cannot make a static reference to the non-static type " + typeParameter.getName(),
ref, TypesPackage.Literals.JVM_PARAMETERIZED_TYPE_REFERENCE__TYPE, -1, STATIC_ACCESS_TO_INSTANCE_MEMBER);
currentParent = currentParent.eContainer();
}
}
}
}
示例11
/**
* Checks whether none is the last arrow shape, since this would create a
* redundant shape
*
* @param arrowType
* The arrowType element to check.
*/
@Check
public void checkIfNoneIsTheLastArrowShape(ArrowType arrowType) {
int numberOfArrowShapes = arrowType.getArrowShapes().size();
if (numberOfArrowShapes > 1) {
AbstractArrowShape lastShape = arrowType.getArrowShapes()
.get(numberOfArrowShapes - 1);
if (lastShape instanceof ArrowShape && ((ArrowShape) lastShape)
.getShape() == PrimitiveShape.NONE) {
reportRangeBasedWarning(INVALID_ARROW_SHAPE_NONE_IS_THE_LAST,
"The shape '" + PrimitiveShape.NONE
+ "' may not be the last shape.",
lastShape,
ArrowtypePackage.Literals.ARROW_SHAPE__SHAPE);
}
}
}
示例12
@Check
public void checkDelegateConstructorIsFirst(XFeatureCall featureCall) {
JvmIdentifiableElement feature = featureCall.getFeature();
if (feature != null && !feature.eIsProxy() && feature instanceof JvmConstructor) {
JvmIdentifiableElement container = logicalContainerProvider.getNearestLogicalContainer(featureCall);
if (container != null) {
if (container instanceof JvmConstructor) {
XExpression body = logicalContainerProvider.getAssociatedExpression(container);
if (body == featureCall)
return;
if (body instanceof XBlockExpression) {
List<XExpression> expressions = ((XBlockExpression) body).getExpressions();
if (expressions.isEmpty() || expressions.get(0) != featureCall) {
error("Constructor call must be the first expression in a constructor", null, INVALID_CONSTRUCTOR_INVOCATION);
}
}
} else {
error("Constructor call must be the first expression in a constructor", null, INVALID_CONSTRUCTOR_INVOCATION);
}
}
}
}
示例13
/**
* Checks that the default severity is within given severity range. There must not be a conflict such
* that the severity range defines severities do not contain the default.
* <p>
* Note that this check works even if {@link #checkSeverityRangeOrder(com.avaloq.tools.ddk.check.check.Check)} is violated.
* </p>
*
* @param check
* the check
*/
@Check
public void checkDefaultSeverityInRange(final com.avaloq.tools.ddk.check.check.Check check) {
if (check.getSeverityRange() == null) {
return; // only applicable if both range and default severity given
}
final SeverityRange range = check.getSeverityRange();
final SeverityKind minSeverity = SeverityKind.get(Math.min(range.getMinSeverity().getValue(), range.getMaxSeverity().getValue()));
final SeverityKind maxSeverity = SeverityKind.get(Math.max(range.getMinSeverity().getValue(), range.getMaxSeverity().getValue()));
if (check.getDefaultSeverity().compareTo(minSeverity) < 0 || check.getDefaultSeverity().compareTo(maxSeverity) > 0) {
List<String> issueCodes = Lists.newArrayList();
SeverityKind temp = minSeverity;
while (temp != null && temp.compareTo(maxSeverity) <= 0) {
issueCodes.add(temp.getName());
temp = SeverityKind.get(temp.getValue() + 1);
}
String[] codes = issueCodes.toArray(new String[issueCodes.size()]);
error(Messages.CheckJavaValidator_DEFAULT_SEVERITY_NOT_IN_RANGE, check, CheckPackage.Literals.CHECK__DEFAULT_SEVERITY, IssueCodes.DEFAULT_SEVERITY_NOT_IN_RANGE, issueCodes.isEmpty()
? null // NOPMD
: codes);
}
}
示例14
/**
* Verifies that a matching default name function exists for scope expressions without explicit name functions.
*
* @param expr
* scope expression to check
*/
@Check
public void checkNameFunctionExists(final SimpleScopeExpression expr) {
if (expr.getNaming() != null && !expr.getNaming().getNames().isEmpty()) {
return;
}
ScopeDefinition def = EObjectUtil.eContainer(expr, ScopeDefinition.class);
ScopeModel model = EObjectUtil.eContainer(expr, ScopeModel.class);
if (def != null && model != null) {
EClass scopeType = getType(def);
NamingSection namingSection = model.getNaming();
if (namingSection != null) {
for (NamingDefinition naming : namingSection.getNamings()) {
if (naming.getType() != null && isLeftMostSuperType(naming.getType(), scopeType)) {
return;
}
}
}
error(NLS.bind(Messages.missingNameFunction, scopeType.getName()), ScopePackage.Literals.SIMPLE_SCOPE_EXPRESSION__EXPR);
}
}
示例15
/**
* Checks that Check Configurations are unique. A Configured Catalog may only contain one configuration for each referenced Check.
*
* @param configuration
* the configuration
*/
@Check
public void checkConfiguredCheckUnique(final ConfiguredCatalog configuration) {
if (configuration.getCheckConfigurations().size() < 2) {
return;
}
Predicate<ConfiguredCheck> predicate = new Predicate<ConfiguredCheck>() {
@Override
public boolean apply(final ConfiguredCheck configuredCheck) {
return configuredCheck.getCheck() != null && !configuredCheck.getCheck().eIsProxy();
}
};
Function<ConfiguredCheck, String> function = new Function<ConfiguredCheck, String>() {
@Override
public String apply(final ConfiguredCheck from) {
return from.getCheck().getName();
}
};
for (final ConfiguredCheck c : getDuplicates(predicate, function, configuration.getCheckConfigurations())) {
error(Messages.CheckCfgJavaValidator_DUPLICATE_CHECK_CONFIGURATION, c, CheckcfgPackage.Literals.CONFIGURED_CHECK__CHECK, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, IssueCodes.DUPLICATE_CHECK_CONFIGURATION);
}
}
示例16
@Check
public void checkInvalidReturnExpression(XExpression expression) {
final EReference contFeature = (EReference) expression.eContainingFeature();
final Map<EReference, EarlyExitKind> map = getDisallowedEarlyExitReferences();
if (map.containsKey(contFeature)) {
EarlyExitKind exitKind = map.get(contFeature);
List<XExpression> returns = newArrayList();
collectExits(expression, returns);
for (XExpression expr : returns) {
if (expr instanceof XReturnExpression && (exitKind == EarlyExitKind.RETURN || exitKind == EarlyExitKind.BOTH)) {
error("A return expression is not allowed in this context.", expr, null, IssueCodes.INVALID_EARLY_EXIT);
}
if (expr instanceof XThrowExpression && (exitKind == EarlyExitKind.THROW || exitKind == EarlyExitKind.BOTH)) {
error("A throw expression is not allowed in this context.", expr, null, IssueCodes.INVALID_EARLY_EXIT);
}
}
}
}
示例17
@Check
public void checkNoMultipleComparators(SimpleVersion simpleVersion) {
EList<VersionComparator> comparators = simpleVersion.getComparators();
if (comparators.size() > 1) {
String msg = SemverIssueCodes.getMessageForSEMVER_TOO_MANY_COMPARATORS();
addIssue(msg, simpleVersion, SemverPackage.Literals.SIMPLE_VERSION__COMPARATORS,
SemverIssueCodes.SEMVER_TOO_MANY_COMPARATORS);
}
}
示例18
/**
* Checks that all variable declarations contained in const statement (expressed by means of a variable statement)
* contain an initializer expression.
*
* IDEBUG-214
*/
@Check
public void checkVariableStatement(VariableStatement variableStatement) {
if (variableStatement.getVarStmtKeyword() == VariableStatementKeyword.CONST) {
variableStatement.getVarDecl().stream().forEach(varDecl -> holdsConstHasInitializer(varDecl));
}
}
示例19
@Check
public void checkTypeNameStartsWithCapital(Entity entity) {
if (!Character.isUpperCase(entity.getName().charAt(0))) {
warning("Name should start with a capital", DomainmodelPackage.Literals.ABSTRACT_ELEMENT__NAME,
ValidationMessageAcceptor.INSIGNIFICANT_INDEX, IssueCodes.INVALID_TYPE_NAME, entity.getName());
}
}
示例20
@Check(CheckType.FAST)
public void checkAndPopulateIssueData(Element element) {
if(element.getName().equals(TRIGGER_VALIDATION_ISSUE)) {
error(
TRIGGER_VALIDATION_ISSUE,
element,
QuickfixCrossrefPackage.Literals.ELEMENT__NAME,
ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
TRIGGER_VALIDATION_ISSUE,
ISSUE_DATA_0,
ISSUE_DATA_1);
}
}
示例21
@Test public void testBug351554_01() throws Exception {
final String text =
"class Foo {\n" +
" @org.eclipse.xtext.validation.Check(org::eclipse::xtext::validation::CheckType::NORMAL)\n" +
" def void checkSomething(Object o) {}\n" +
"}";
Check check = getAnnotationOnMethod(text, Check.class);
assertNotNull(check);
assertEquals(CheckType.NORMAL, check.value());
}
示例22
/**
* Composed check for {@link EnumLiteralDeclaration}.
*
* @param n4EnumDeclaration
* whose literals will be validated
*/
@Check
public void checkEnumLiterals(N4EnumDeclaration n4EnumDeclaration) {
Set<String> builtInEnumMembersNames = findBuiltInN4EnumMembers(n4EnumDeclaration);
internalCheckNotInStaticPolyfillModule(n4EnumDeclaration, this);
n4EnumDeclaration
.getLiterals()
.stream()
.filter(it -> it.getName() != null)
.collect(Collectors.groupingBy(N4EnumLiteral::getName))
.forEach(
(name, literals) -> {
// reduce number of issues, not all checks may be triggered
// check enum literals duplicates
if (literals.size() > 1) {
addIssue(getMessageForENM_DUPLICTAE_LITERALS(name), literals.get(0),
N4JSPackage.Literals.N4_ENUM_LITERAL__NAME,
ENM_DUPLICTAE_LITERALS);
return;// one issue at the time!
}
// check enum literal name clash with meta property
if (builtInEnumMembersNames.contains(name)) {
addIssue(getMessageForENM_LITERALS_HIDE_META(name), literals.get(0),
N4JSPackage.Literals.N4_ENUM_LITERAL__NAME,
ENM_LITERALS_HIDE_META);
}
});
}
示例23
/**
* Checks that there is an interface specification matching the given navigation.
*
* @param context
* navigation to check
*/
@Check
public void checkReferencedInterfaceDeclared(final InterfaceNavigation context) {
if (context.getRef() == null || context.getRef().getEReferenceType() == null) {
return;
}
ExportModel model = EObjectUtil.eContainer(context, ExportModel.class);
EClass type = context.getRef().getEReferenceType();
if (findMatchingInterfaces(model, type).isEmpty()) {
error("No interface specification declared matching type " + type.getName(), ExportPackage.Literals.INTERFACE_NAVIGATION__REF);
}
}
示例24
/**
* Checks that a final check does not allow defining a severity range.
*
* @param check
* the check to be checked
*/
@Check
public void checkSeverityRangesNotAllowedForFinalCheck(final com.avaloq.tools.ddk.check.check.Check check) {
if (check.isFinal() && check.getSeverityRange() != null) {
error(Messages.CheckJavaValidator_NO_SEVERITY_RANGE_FOR_FINAL_CHECK, check, CheckPackage.Literals.CHECK__FINAL, IssueCodes.SEVERITY_RANGES_FOR_FINAL_CHECK);
}
}
示例25
/**
* Checks that final catalogs are not configured for severity.
*
* @see {@link com.avaloq.tools.ddk.check.check.CheckCatalog#isFinal()}
* @param catalog
* the configured catalog
*/
@Check
public void checkFinalCatalogNotConfigurable(final ConfiguredCatalog catalog) {
if (catalog.getCatalog() != null && !catalog.getCatalog().eIsProxy() && catalog.getCatalog().isFinal()) {
for (final ConfiguredCheck check : catalog.getCheckConfigurations()) {
if (isSeverityConfigured(check)) {
error(Messages.CheckCfgJavaValidator_FINAL_CATALOG_NOT_CONFIGURABLE, check, null, IssueCodes.FINAL_CATALOG_NOT_CONFIGURABLE);
}
}
}
}
示例26
/**
* Verifies that the given check can be interpreted as Java identifier.
*
* @param check
* the check to validate
*/
@Check
public void checkCheckName(final com.avaloq.tools.ddk.check.check.Check check) {
final String name = check.getName();
if (Strings.isEmpty(name)) {
error(NLS.bind(Messages.CheckJavaValidator_ID_MISSING, CHECK, check.getLabel()), check, locationInFileProvider.getIdentifierFeature(check), IssueCodes.MISSING_ID_ON_CHECK, check.getLabel());
} else {
final IStatus status = javaValidatorUtil.checkCheckName(name);
if (!status.isOK()) {
issue(status, status.getMessage(), check, locationInFileProvider.getIdentifierFeature(check), IssueCodes.INVALID_CHECK_NAME);
}
}
}
示例27
@Check
protected void checkModifiers(XtendAnnotationType annotation) {
EObject eContainer = annotation.eContainer();
if (eContainer instanceof XtendFile) {
annotationTypeModifierValidator.checkModifiers(annotation, "annotation type " + annotation.getName());
} else {
nestedAnnotationTypeModifierValidator.checkModifiers(annotation, "annotation type " + annotation.getName());
}
}
示例28
@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);
}
}
}
示例29
/**
* Check that imports from packages designated as "API" in an extension point check API specification. If no specification, ignore.
*
* @param importSection
* import to be validated
*/
@Check
public void checkImportNonPublicApi(final XImportSection importSection) {
if (!PUBLIC_API.isEmpty()) {
importSection.getImportDeclarations().forEach(xImport -> {
if (xImport.isWildcard()) {
// We know this isn't null and ends with .* from the "isWildcard"
String nameSpace = xImport.getImportedNamespace();
validatePackageAccess(nameSpace.substring(0, nameSpace.length() - 2), xImport, XtypePackage.Literals.XIMPORT_DECLARATION__IMPORTED_TYPE);
} else if (xImport.getImportedType() != null) {
validatePackageAccess(xImport.getImportedType().getPackageName(), xImport, XtypePackage.Literals.XIMPORT_DECLARATION__IMPORTED_TYPE);
}
});
}
}
示例30
@Check
public void checkTernaryExpressionUsed(XIfExpression exp) {
if (exp.isConditionalExpression()) {
//Check if this expression is nested in another already marked ternary expression
EObject container = exp.eContainer();
if (container instanceof XIfExpression && ((XIfExpression) container).isConditionalExpression()) {
return;
}
//Raise issue
addIssue("The ternary operator is not allowed. Use a normal if-expression.", exp, TERNARY_EXPRESSION_NOT_ALLOWED);
}
}