Java Code Examples for org.eclipse.xtext.EcoreUtil2#eAllOfType()

The following examples show how to use org.eclipse.xtext.EcoreUtil2#eAllOfType() . 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: ArithmeticExtensionsTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void assertOnlyPrimitiveOperationsBound(XExpression expression) {
	boolean operationsFound = false;
	for (XAbstractFeatureCall featureCall : EcoreUtil2.eAllOfType(expression, XAbstractFeatureCall.class)) {
		JvmIdentifiableElement feature = featureCall.getFeature();
		if (feature instanceof JvmOperation) {
			for (JvmFormalParameter parameter : ((JvmOperation) feature).getParameters()) {
				operationsFound = true;
				assertTrue(parameter.getParameterType().getIdentifier(),
						primitives.isPrimitive(parameter.getParameterType()));
			}
		}
	}
	assertTrue("No operations found", operationsFound);
}
 
Example 2
Source File: DomainmodelCodeMiningProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void createCodeMinings(IDocument document, XtextResource resource, CancelIndicator indicator,
		IAcceptor<? super ICodeMining> acceptor) throws BadLocationException {
	if (resource.getContents().isEmpty()) {
		return;
	}
	// get all operations to open document
	List<Operation> allOperations = EcoreUtil2.eAllOfType(resource.getContents().get(0), Operation.class);
	// get keyword for ')'
	Keyword rightParenthesisKeyword_4 = grammar.getOperationAccess().getRightParenthesisKeyword_4();
	for (Operation o : allOperations) {
		//inline annotations only for methods with no return type
		if (o.getType() != null) {
			continue;
		}
		// get return type name from operation
		JvmOperation inferredOp = (JvmOperation) jvmModelAssociations.getPrimaryJvmElement(o);
		if (inferredOp == null || inferredOp.getReturnType() == null) {
			continue; // broken model
		}
		String returnTypeName = inferredOp.getReturnType().getSimpleName();
		// find document offset for inline annotation
		ICompositeNode node = NodeModelUtils.findActualNodeFor(o);
		for (Iterator<INode> it = node.getAsTreeIterable().iterator(); it.hasNext();) {
			INode child = it.next();
			if (rightParenthesisKeyword_4.equals(child.getGrammarElement())) {
				// create line content code mining for inline annotation after grammarElement ')'
				String annotationText = " : " + returnTypeName;
				acceptor.accept(createNewLineContentCodeMining(child.getTotalOffset() + 1, annotationText));
			}
		}
	}
}
 
Example 3
Source File: ArithmeticsCodeMiningProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void createCodeMinings(IDocument document, XtextResource resource, CancelIndicator indicator,
	IAcceptor<? super ICodeMining> acceptor) throws BadLocationException {

	EList<EObject> contents = resource.getContents();
	if (contents.isEmpty()) {
		return;
	}

	// get all evaluations contained by the open document
	List<Evaluation> allEvaluations = EcoreUtil2.eAllOfType(contents.get(0), Evaluation.class);

	// get keyword for ';'
	Keyword semicolon = grammar.getEvaluationAccess().getSemicolonKeyword_1();

	for (Evaluation evaluation : allEvaluations) {
		ICompositeNode node = NodeModelUtils.findActualNodeFor(evaluation);
		for (Iterator<INode> it = node.getAsTreeIterable().iterator(); it.hasNext();) {
			INode child = it.next();
			if (semicolon.equals(child.getGrammarElement())) {
				int annotationOffset = child.getTotalOffset();
				String annotationText = getAnnotationText(evaluation);
				acceptor.accept(createNewLineContentCodeMining(annotationOffset, annotationText));
			}
		}
	}
}
 
Example 4
Source File: XtendFileRenameParticipant.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected List<? extends IRenameElementContext> createRenameElementContexts(Object element) {
	if(super.getNewName().endsWith(".xtend")) {
		IFile file = (IFile) element;
		final IPath filePath = file.getFullPath();
		final IPath newPath = file.getFullPath().removeLastSegments(1).append(getNewName() + ".xtend");
		String className = trimFileExtension(file.getName());
		if(className != null) {
			ResourceSet resourceSet = resourceSetProvider.get(file.getProject());
			URI resourceURI = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
			Resource resource = resourceSet.getResource(resourceURI, true);
			if (resource != null && !resource.getContents().isEmpty()) {
				for (XtendTypeDeclaration type : EcoreUtil2.eAllOfType(resource.getContents().get(0), XtendTypeDeclaration.class)) {
					if (equal(className, type.getName())) {
						IRenameElementContext renameElementContext = renameContextFactory.createRenameElementContext(type, null, null,
								(XtextResource) resource);
						if(renameElementContext instanceof IChangeRedirector.Aware) 
							((IChangeRedirector.Aware) renameElementContext).setChangeRedirector(new IChangeRedirector() {
								@Override
								public IPath getRedirectedPath(IPath source) {
									return source.equals(filePath) ? newPath : source;
								}
								
							});
						return singletonList(renameElementContext);
					}
				}
			}
		}
	}
	return super.createRenameElementContexts(element);
}
 
Example 5
Source File: AbstractNFAState.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<T> getAllIncoming() {
	for (Adapter a : element.eResource().eAdapters())
		if (a instanceof IsInitializedMarker && ((IsInitializedMarker) a).builder == builder)
			return getIncoming();
	element.eResource().eAdapters().add(new IsInitializedMarker(builder));
	for (EObject root : element.eResource().getContents())
		if (root instanceof Grammar)
			for (AbstractRule rule : ((Grammar) root).getRules())
				if (GrammarUtil.isEObjectRule(rule))
					for (AbstractElement ele : EcoreUtil2.eAllOfType(rule, AbstractElement.class))
						if (!builder.filter(ele))
							builder.getState(ele).getOutgoing();
	return getIncoming();
}
 
Example 6
Source File: CheckJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks that if guards have been provided as part of a context's constraint, they appear in the
 * beginning of a block expression.
 *
 * @param context
 *          the context for which the constraint is checked
 */
@SuppressWarnings("unchecked")
@Check
public void checkGuardsFirst(final Context context) {
  if (context.getContextVariable() == null || context.getConstraint() == null) {
    return;
  }

  List<XGuardExpression> guards = EcoreUtil2.eAllOfType(context.getConstraint(), XGuardExpression.class);
  if (Iterables.isEmpty(guards)) {
    return; // no guards makes check irrelevant
  }

  EList<XExpression> topLevelExpressions = (EList<XExpression>) ((XBlockExpression) context.getConstraint()).eGet(XbasePackage.Literals.XBLOCK_EXPRESSION__EXPRESSIONS);

  for (final XGuardExpression guard : guards) {
    final EStructuralFeature eContainingFeature = guard.eContainingFeature();
    if (guard.eContainer() != null && eContainingFeature != null) {
      if (guard.eContainer().eGet(eContainingFeature) != topLevelExpressions) {
        // guards not allowed in nested expressions, must be on root level
        error(Messages.CheckJavaValidator_GUARDS_COME_FIRST, guard, null, IssueCodes.GUARDS_COME_FIRST);
      } else {
        // check that guards precede other expressions
        int pos = topLevelExpressions.indexOf(guard);
        if (pos > 0) {
          for (int i = 0; i < pos; i++) {
            if (!(topLevelExpressions.get(i) instanceof XGuardExpression)) {
              error(Messages.CheckJavaValidator_GUARDS_COME_FIRST, guard, null, IssueCodes.GUARDS_COME_FIRST);
              break;
            }
          }
        }
      }
    }
  }
}
 
Example 7
Source File: BalzacCodeMiningProvider.java    From balzac with Apache License 2.0 4 votes vote down vote up
@Override
protected void createCodeMinings(
    IDocument document,
    XtextResource resource,
    CancelIndicator indicator,
    IAcceptor<? super ICodeMining> acceptor) throws BadLocationException {

    // get all operations to open document
    List<Constant> allConstants = EcoreUtil2.eAllOfType(resource.getContents().get(0), Constant.class);

    Keyword colon = grammar.getConstantAccess().getColonKeyword_2_0();
    Keyword equalsSign = grammar.getConstantAccess().getEqualsSignKeyword_3();

    for (Constant c : allConstants) {
        // find document offset for inline annotation
        ICompositeNode node = NodeModelUtils.findActualNodeFor(c);

        boolean hasType = false;
        for (Iterator<INode> it = node.getAsTreeIterable().iterator(); it.hasNext();) {
            INode child = it.next();
            if (colon.equals(child.getGrammarElement())) {
                hasType = true;
            }
            if (!hasType && equalsSign.equals(child.getGrammarElement())) {
                // create line content code mining for inline annotation after grammarElement
                // ')'
                Result<Type> res = typeSystem.typeExpression(new TypeSubstitutions(), c);
                if (!res.failed()) {
                    String annotationText = ": " + strRep.stringRep(res.getFirst()) + " ";
                    acceptor.accept(createNewLineContentCodeMining(child.getTotalOffset(), annotationText));
                }
            }
        }
    }

    // TODO: implement me
    // use acceptor.accept(super.createNewLineHeaderCodeMining(...)) to add a new
    // code mining to the
    // final list

    // example:
    // acceptor.accept(createNewLineHeaderCodeMining(1, document, "Header
    // annotation"));
}
 
Example 8
Source File: SARLCodeMiningProvider.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Add an annotation when the action's return type is implicit and inferred by the SARL compiler.
 *
 * @param resource the resource to parse.
 * @param acceptor the code mining acceptor.
 */
@SuppressWarnings("checkstyle:npathcomplexity")
private void createImplicitActionReturnType(XtextResource resource, IAcceptor<? super ICodeMining> acceptor) {
	final List<XtendFunction> actions = EcoreUtil2.eAllOfType(resource.getContents().get(0), XtendFunction.class);

	for (final XtendFunction action : actions) {
		// inline annotation only for methods with no return type
		if (action.getReturnType() != null) {
			continue;
		}
		// get return type name from operation
		final JvmOperation inferredOperation = (JvmOperation) this.jvmModelAssocitions.getPrimaryJvmElement(action);
		if (inferredOperation == null || inferredOperation.getReturnType() == null) {
			continue;
		}
		// find document offset for inline annotationn
		final ICompositeNode node = NodeModelUtils.findActualNodeFor(action);
		final Keyword parenthesis = this.grammar.getAOPMemberAccess().getRightParenthesisKeyword_2_5_6_2();
		final Assignment fctname = this.grammar.getAOPMemberAccess().getNameAssignment_2_5_5();
		int offsetFctname = -1;
		int offsetParenthesis = -1;
		for (Iterator<INode> it = node.getAsTreeIterable().iterator(); it.hasNext();) {
			final INode child = it.next();
			if (child != node) {
				final EObject grammarElement = child.getGrammarElement();
				if (grammarElement instanceof RuleCall) {
					if (fctname.equals(grammarElement.eContainer())) {
						offsetFctname = child.getTotalEndOffset();
					}
				} else if (parenthesis.equals(grammarElement)) {
					offsetParenthesis = child.getTotalEndOffset();
					break;
				}
			}
		}
		int offset = -1;
		if (offsetParenthesis >= 0) {
			offset = offsetParenthesis;
		} else if (offsetFctname >= 0) {
			offset = offsetFctname;
		}
		if (offset >= 0) {
			final String returnType = inferredOperation.getReturnType().getSimpleName();
			final String text = " " + this.keywords.getColonKeyword() + " " + returnType; //$NON-NLS-1$ //$NON-NLS-2$
			acceptor.accept(createNewLineContentCodeMining(offset, text));
		}
	}
}