org.eclipse.xtext.validation.Check Java Examples

The following examples show how to use org.eclipse.xtext.validation.Check. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CheckJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #2
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@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);
		}
	}
}
 
Example #3
Source File: ScopeJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #4
Source File: DotHtmlLabelValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example #5
Source File: ExportJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
    }
  }
}
 
Example #6
Source File: CheckCfgJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
  }

}
 
Example #7
Source File: N4JSNameValidator.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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
	}
}
 
Example #8
Source File: RuleEngineValidator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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);
					}
				}
			}
	}
}
 
Example #9
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@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();
			}
		}
	}
}
 
Example #10
Source File: XtextValidator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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;
		}
	}
}
 
Example #11
Source File: CheckJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #12
Source File: DotArrowTypeValidator.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example #13
Source File: EarlyExitValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@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);
			}
		}
	}
}
 
Example #14
Source File: XtextValidator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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);
			}
		}
	}
}
 
Example #15
Source File: N4JSStatementValidator.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);

	}
}
 
Example #16
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@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);
			}
		}
	}
}
 
Example #17
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@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);
				}
			}
		}
	}
}
 
Example #18
Source File: ValidJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check that the label of a rule doesn't end with a dot.
 *
 * @param rule
 *          the rule
 */
@Check(CheckType.FAST)
public void checkRuleLabelEndsWithDot(final Rule rule) {
  guard(rule.getLabel().length() > 0);
  if (rule.getLabel().endsWith(DOT)) {
    warning(LABEL_SHOULD_NOT_END_WITH_A_DOT, ValidPackage.Literals.RULE__LABEL, RULE_LABEL_ENDS_WITH_DOT);
  }
}
 
Example #19
Source File: XbaseUIValidator.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkRestrictedType(XImportDeclaration importDeclaration){
	if (isRestrictionCheckIgnored())
		return;
	JvmType importedType = importDeclaration.getImportedType();
	if(importedType instanceof JvmDeclaredType)
		checkRestrictedType(importDeclaration, XtypePackage.Literals.XIMPORT_DECLARATION__IMPORTED_TYPE, (JvmDeclaredType) importedType);
}
 
Example #20
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example #21
Source File: TemplateValidator.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkParameters(Variable variable) {
	Codetemplate template = EcoreUtil2.getContainerOfType(variable, Codetemplate.class);
	Codetemplates templates = EcoreUtil2.getContainerOfType(template, Codetemplates.class);
	if (templates != null && template != null) {
		Grammar language = templates.getLanguage();
		AbstractRule rule = template.getContext();
		ContextTypeIdHelper helper = languageRegistry.getContextTypeIdHelper(language);
		if (helper != null && rule != null && !rule.eIsProxy() && rule instanceof ParserRule) {
			String contextTypeId = helper.getId(rule);
			ContextTypeRegistry contextTypeRegistry = languageRegistry.getContextTypeRegistry(language);
			TemplateContextType contextType = contextTypeRegistry.getContextType(contextTypeId);
			if (contextType != null) {
				Iterator<TemplateVariableResolver> resolvers = Iterators.filter(contextType.resolvers(),
						TemplateVariableResolver.class);
				String type = variable.getType();
				if (type == null)
					type = variable.getName();
				while (resolvers.hasNext()) {
					final TemplateVariableResolver resolver = resolvers.next();
					if (resolver.getType().equals(type)) {
						IInspectableTemplateVariableResolver inspectableResolver = registry
								.toInspectableResolver(resolver);
						if (inspectableResolver != null) {
							inspectableResolver.validateParameters(variable, this);
						}
					}
				}
			}
		}
	}
}
 
Example #22
Source File: AnnotationValidation.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkAnnotation(final XtendAnnotationType it) {
  Iterable<XtendField> _filter = Iterables.<XtendField>filter(it.getMembers(), XtendField.class);
  for (final XtendField it_1 : _filter) {
    {
      boolean _isValidAnnotationValueType = this.isValidAnnotationValueType(it_1.getType());
      boolean _not = (!_isValidAnnotationValueType);
      if (_not) {
        StringConcatenation _builder = new StringConcatenation();
        _builder.append("Invalid type ");
        String _simpleName = it_1.getType().getSimpleName();
        _builder.append(_simpleName);
        _builder.append(" for the annotation attribute ");
        String _name = it_1.getName();
        _builder.append(_name);
        _builder.append("; only primitive type, String, Class, annotation, enumeration are permitted or 1-dimensional arrays thereof");
        this.error(_builder.toString(), it_1, 
          XtendPackage.Literals.XTEND_FIELD__TYPE, 
          IssueCodes.INVALID_ANNOTATION_VALUE_TYPE);
      }
      XExpression _initialValue = it_1.getInitialValue();
      boolean _tripleNotEquals = (_initialValue != null);
      if (_tripleNotEquals) {
        this.annotationValueValidator.validateAnnotationValue(it_1.getInitialValue(), this);
      }
    }
  }
}
 
Example #23
Source File: XtextValidator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkGeneratedPackageForNameClashes(GeneratedMetamodel metamodel) {
	EPackage pack = metamodel.getEPackage();
	Multimap<String, ENamedElement> constantNameToElement = HashMultimap.create();
	Multimap<String, ENamedElement> accessorNameToElement = HashMultimap.create();
	if (pack != null) {
		for(EClassifier classifier: pack.getEClassifiers()) {
			String accessorName = classifier.getName();
			if ("Class".equals(accessorName) || "Name".equals(accessorName))
				accessorName += "_";
			accessorNameToElement.put("get" + accessorName, classifier);
			String classifierConstantName = CodeGenUtil2.format(classifier.getName(), '_', null, true, true).toUpperCase();
			constantNameToElement.put(classifierConstantName, classifier);
			if (classifier instanceof EClass) {
				for(EStructuralFeature feature: ((EClass) classifier).getEAllStructuralFeatures()) {
					String featureConstantPart = CodeGenUtil2.format(feature.getName(), '_', null, false, false).toUpperCase();
					String featureConstantName = classifierConstantName + "__" + featureConstantPart;
					constantNameToElement.put(featureConstantName, feature);
					String featureAccessorName = "get" + classifier.getName() + "_" + Strings.toFirstUpper(feature.getName());
					accessorNameToElement.put(featureAccessorName, feature);
				}
			}
		}
	}
	createMessageForNameClashes(constantNameToElement);
	createMessageForNameClashes(accessorNameToElement);
}
 
Example #24
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkNoReturnsInCreateExtensions(XtendFunction func) {
	if (func.getCreateExtensionInfo() == null)
		return;
	List<XReturnExpression> found = newArrayList();
	collectReturnExpressions(func.getCreateExtensionInfo().getCreateExpression(), found);
	for (XReturnExpression xReturnExpression : found) {
		error("Return is not allowed in creation expression", xReturnExpression, null, INVALID_EARLY_EXIT);
	}
}
 
Example #25
Source File: ValidJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check that the native context type has no feature if a marker type is present.
 *
 * @param nativeContext
 *          the native context
 */
@Check(CheckType.FAST)
public void checkNativeContextContextFeature(final NativeContext nativeContext) {
  guard(nativeContext.getContextFeature() != null);
  if (nativeContext.getMarkerType() != null) {
    error(CONTEXT_FEATURE_CANNOT_BE_SPECIFIED_IF_A_MARKER_TYPE_IS_GIVEN, ValidPackage.Literals.CONTEXT__CONTEXT_FEATURE, NATIVE_CONTEXT_CONTEXT_FEATURE);
  }
}
 
Example #26
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkLocalUsageOfSwitchParameter(XSwitchExpression switchExpression) {
	JvmFormalParameter switchParam = switchExpression.getDeclaredParam();
	if(!isIgnored(UNUSED_LOCAL_VARIABLE) && switchParam != null && !isLocallyUsed(switchParam, switchExpression)){
		String message = "The value of the local variable " + switchParam.getName() + " is not used";
		addIssue(message, switchParam, TypesPackage.Literals.JVM_FORMAL_PARAMETER__NAME, UNUSED_LOCAL_VARIABLE);
	}
}
 
Example #27
Source File: QuickfixCrossrefTestLanguageValidator.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Check(CheckType.FAST)
public void checkDocumentation(Element element) {
	if (element.getDoc().equals("no doc")) {
		warning(MULTIFIXABLE_ISSUE, element, QuickfixCrossrefPackage.Literals.ELEMENT__DOC,
				ValidationMessageAcceptor.INSIGNIFICANT_INDEX, MULTIFIXABLE_ISSUE);
	}
}
 
Example #28
Source File: CheckJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Verifies that the given catalog can be interpreted as Java identifier.
 *
 * @param catalog
 *          the catalog to validate
 */
@Check
public void checkCatalogName(final CheckCatalog catalog) {
  if (!Strings.isEmpty(catalog.getName())) {
    IStatus status = javaValidatorUtil.checkCatalogName(catalog.getName());
    if (!status.isOK()) {
      issue(status, status.getMessage(), catalog, CheckPackage.Literals.CHECK_CATALOG__NAME, IssueCodes.INVALID_CATALOG_NAME);
    }
  }
}
 
Example #29
Source File: LibraryChecksCheckImpl.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * checkCatalogIsActiveGreeting.
 */
@Check(CheckType.FAST)
public void checkCatalogIsActiveGreeting(final Greeting it) {// Issue diagnostic
  libraryChecksCatalog.accept(getMessageAcceptor(), //
    it, // context EObject
    null, // EStructuralFeature
    libraryChecksCatalog.getCheckCatalogIsActiveMessage(), // Message
    libraryChecksCatalog.getCheckCatalogIsActiveSeverityKind(it), // Severity 
    ValidationMessageAcceptor.INSIGNIFICANT_INDEX, // Marker index
    LibraryChecksIssueCodes.CHECK_CATALOG_IS_ACTIVE // Issue code & data
  );
}
 
Example #30
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkNoForwardReferences(XExpression fieldInitializer) {
	JvmIdentifiableElement container = logicalContainerProvider.getLogicalContainer(fieldInitializer);
	if (container instanceof JvmField) {
		JvmField field = (JvmField) container;
		boolean staticField = field.isStatic();
		JvmDeclaredType declaredType = field.getDeclaringType();
		if (declaredType == null) {
			return;
		}
		Collection<JvmField> illegalFields = Sets.newHashSet();
		for(int i = declaredType.getMembers().size() - 1; i>=0; i--) {
			JvmMember member = declaredType.getMembers().get(i);
			if (member instanceof JvmField) {
				if (((JvmField) member).isStatic() == staticField) {
					illegalFields.add((JvmField) member);
				}
			}
			if (member == field)
				break;
		}
		TreeIterator<EObject> iterator = EcoreUtil2.eAll(fieldInitializer);
		while(iterator.hasNext()) {
			EObject object = iterator.next();
			if (object instanceof XFeatureCall) {
				JvmIdentifiableElement feature = ((XFeatureCall) object).getFeature();
				if (illegalFields.contains(((XFeatureCall) object).getFeature())) {
					error("Cannot reference the field '" + feature.getSimpleName() + "' before it is defined", 
							object, null, INSIGNIFICANT_INDEX, ILLEGAL_FORWARD_REFERENCE);
				}
			} else if (isLocalClassSemantics(object)) {
				iterator.prune();
			}
		}
	}
}