Search in sources :

Example 6 with Keyword

use of org.eclipse.xtext.Keyword in project xtext-eclipse by eclipse.

the class GrammarTest method checkConcreteImplRule.

private AbstractRule checkConcreteImplRule(Grammar grammar, String ruleName) {
    AbstractRule concreteRule = GrammarUtil.findRuleForName(grammar, ruleName);
    assertNotNull(concreteRule);
    EClassifier returnType = ((ParserRule) concreteRule).getType().getClassifier();
    String returnTypeName = getClassifierName(returnType);
    assertEquals(ruleName, returnTypeName + "_Impl");
    List<Assignment> assignments = GrammarUtil.containedAssignments(concreteRule);
    assertEquals(1, assignments.size());
    assertEquals("name", assignments.get(0).getFeature());
    assertEquals("=", assignments.get(0).getOperator());
    List<Action> containedActions = GrammarUtil.containedActions(concreteRule);
    assertEquals(1, containedActions.size());
    assertEquals(returnTypeName, getClassifierName(containedActions.get(0).getType().getClassifier()));
    List<Keyword> containedKeywords = GrammarUtil.containedKeywords(concreteRule);
    assertEquals(1, containedKeywords.size());
    assertEquals(returnTypeName, containedKeywords.get(0).getValue());
    return concreteRule;
}
Also used : Assignment(org.eclipse.xtext.Assignment) Action(org.eclipse.xtext.Action) Keyword(org.eclipse.xtext.Keyword) EClassifier(org.eclipse.emf.ecore.EClassifier) AbstractRule(org.eclipse.xtext.AbstractRule)

Example 7 with Keyword

use of org.eclipse.xtext.Keyword in project xtext-eclipse by eclipse.

the class DomainmodelCodeMiningProvider method createCodeMinings.

@Override
protected void createCodeMinings(IDocument document, XtextResource resource, CancelIndicator indicator, IAcceptor<? super ICodeMining> acceptor) throws BadLocationException {
    // 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) {
            // broken model
            continue;
        }
        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));
            }
        }
    }
}
Also used : JvmOperation(org.eclipse.xtext.common.types.JvmOperation) INode(org.eclipse.xtext.nodemodel.INode) Keyword(org.eclipse.xtext.Keyword) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) JvmOperation(org.eclipse.xtext.common.types.JvmOperation) Operation(org.eclipse.xtext.example.domainmodel.domainmodel.Operation)

Example 8 with Keyword

use of org.eclipse.xtext.Keyword in project xtext-eclipse by eclipse.

the class DefaultQuickfixProvider method createLinkingIssueResolutions.

public void createLinkingIssueResolutions(final Issue issue, final IssueResolutionAcceptor issueResolutionAcceptor) {
    final IModificationContext modificationContext = modificationContextFactory.createModificationContext(issue);
    final IXtextDocument xtextDocument = modificationContext.getXtextDocument();
    if (xtextDocument == null)
        return;
    xtextDocument.readOnly(new CancelableUnitOfWork<Void, XtextResource>() {

        IssueResolutionAcceptor myAcceptor = null;

        @Override
        public java.lang.Void exec(XtextResource state, CancelIndicator cancelIndicator) throws Exception {
            myAcceptor = getCancelableAcceptor(issueResolutionAcceptor, cancelIndicator);
            EObject target = state.getEObject(issue.getUriToProblem().fragment());
            EReference reference = getUnresolvedEReference(issue, target);
            if (reference == null)
                return null;
            fixUnresolvedReference(issue, xtextDocument, target, reference);
            return null;
        }

        protected void fixUnresolvedReference(final Issue issue, final IXtextDocument xtextDocument, EObject target, EReference reference) throws BadLocationException {
            boolean caseInsensitive = caseInsensitivityHelper.isIgnoreCase(reference);
            EObject crossReferenceTerminal = getCrossReference(issue, target);
            String ruleName = null;
            Keyword keyword = null;
            if (crossReferenceTerminal instanceof RuleCall) {
                RuleCall ruleCall = (RuleCall) crossReferenceTerminal;
                ruleName = ruleCall.getRule().getName();
            } else if (crossReferenceTerminal instanceof Keyword) {
                keyword = (Keyword) crossReferenceTerminal;
            }
            String issueString = xtextDocument.get(issue.getOffset(), issue.getLength());
            IScope scope = scopeProvider.getScope(target, reference);
            List<IEObjectDescription> discardedDescriptions = Lists.newArrayList();
            Set<String> qualifiedNames = Sets.newHashSet();
            int addedDescriptions = 0;
            int checkedDescriptions = 0;
            for (IEObjectDescription referableElement : queryScope(scope)) {
                String referableElementQualifiedName = qualifiedNameConverter.toString(referableElement.getQualifiedName());
                if (similarityMatcher.isSimilar(issueString, qualifiedNameConverter.toString(referableElement.getName()))) {
                    addedDescriptions++;
                    createResolution(issueString, referableElement, ruleName, keyword, caseInsensitive);
                    qualifiedNames.add(referableElementQualifiedName);
                } else {
                    if (qualifiedNames.add(referableElementQualifiedName))
                        discardedDescriptions.add(referableElement);
                }
                checkedDescriptions++;
                if (checkedDescriptions > 100)
                    break;
            }
            if (discardedDescriptions.size() + addedDescriptions <= 5) {
                for (IEObjectDescription referableElement : discardedDescriptions) {
                    createResolution(issueString, referableElement, ruleName, keyword, caseInsensitive);
                }
            }
        }

        protected AbstractElement getCrossReference(final Issue issue, EObject target) {
            final ICompositeNode node = NodeModelUtils.getNode(target);
            if (node == null)
                throw new IllegalStateException("Cannot happen since we found a reference");
            ICompositeNode rootNode = node.getRootNode();
            ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, issue.getOffset());
            CrossReference crossReference = findCrossReference(target, leaf);
            return crossReference.getTerminal();
        }

        public void createResolution(String issueString, IEObjectDescription solution, String ruleName, Keyword keyword, boolean caseInsensitive) {
            String replacement = qualifiedNameConverter.toString(solution.getName());
            String replaceLabel = fixCrossReferenceLabel(issueString, replacement);
            if (keyword != null) {
                if (caseInsensitive && !replacement.equalsIgnoreCase(keyword.getValue()))
                    return;
                if (!caseInsensitive && !replacement.equals(keyword.getValue()))
                    return;
            } else if (ruleName != null) {
                replacement = converter.convertToString(replacement, ruleName);
                if (replacement == null) {
                    return;
                }
            } else {
                logger.error("either keyword or ruleName have to present", new IllegalStateException());
            }
            myAcceptor.accept(issue, replaceLabel, replaceLabel, fixCrossReferenceImage(issueString, replacement), new ReplaceModification(issue, replacement));
        }
    });
}
Also used : Issue(org.eclipse.xtext.validation.Issue) Set(java.util.Set) XtextResource(org.eclipse.xtext.resource.XtextResource) RuleCall(org.eclipse.xtext.RuleCall) IEObjectDescription(org.eclipse.xtext.resource.IEObjectDescription) ILeafNode(org.eclipse.xtext.nodemodel.ILeafNode) EObject(org.eclipse.emf.ecore.EObject) IScope(org.eclipse.xtext.scoping.IScope) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) ArrayList(java.util.ArrayList) List(java.util.List) EReference(org.eclipse.emf.ecore.EReference) Keyword(org.eclipse.xtext.Keyword) AbstractElement(org.eclipse.xtext.AbstractElement) BadLocationException(org.eclipse.jface.text.BadLocationException) ValueConverterException(org.eclipse.xtext.conversion.ValueConverterException) IModificationContext(org.eclipse.xtext.ui.editor.model.edit.IModificationContext) CrossReference(org.eclipse.xtext.CrossReference) CancelIndicator(org.eclipse.xtext.util.CancelIndicator) BadLocationException(org.eclipse.jface.text.BadLocationException) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 9 with Keyword

use of org.eclipse.xtext.Keyword in project xtext-core by eclipse.

the class KeywordInspector method inspectKeywordHidesTerminalRule.

public void inspectKeywordHidesTerminalRule(Keyword keyword) {
    AbstractRule container = GrammarUtil.containingRule(keyword);
    if (container instanceof TerminalRule)
        return;
    Grammar grammar = GrammarUtil.getGrammar(container);
    List<TerminalRule> rules = GrammarUtil.allTerminalRules(grammar);
    for (TerminalRule rule : rules) {
        if (!rule.isFragment()) {
            AbstractElement element = rule.getAlternatives();
            if (element instanceof Keyword && Strings.isEmpty(element.getCardinality())) {
                String value = ((Keyword) element).getValue();
                if (value.equals(keyword.getValue()))
                    acceptor.acceptError("The keyword '" + value + "' hides the terminal rule " + rule.getName() + ".", keyword, XtextPackage.Literals.KEYWORD__VALUE, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, null);
            }
        }
    }
}
Also used : AbstractElement(org.eclipse.xtext.AbstractElement) Keyword(org.eclipse.xtext.Keyword) Grammar(org.eclipse.xtext.Grammar) TerminalRule(org.eclipse.xtext.TerminalRule) AbstractRule(org.eclipse.xtext.AbstractRule)

Example 10 with Keyword

use of org.eclipse.xtext.Keyword in project xtext-core by eclipse.

the class XtextFormatter method configureFormatting.

@Override
protected void configureFormatting(FormattingConfig cfg) {
    XtextGrammarAccess g = (XtextGrammarAccess) getGrammarAccess();
    cfg.setAutoLinewrap(120);
    // Comments
    cfg.setLinewrap(0, 1, 2).before(g.getSL_COMMENTRule());
    cfg.setLinewrap(0, 1, 2).before(g.getML_COMMENTRule());
    cfg.setLinewrap(0, 1, 1).after(g.getML_COMMENTRule());
    // general keywords
    for (Pair<Keyword, Keyword> pair : g.findKeywordPairs("(", ")")) {
        cfg.setNoSpace().after(pair.getFirst());
        cfg.setNoSpace().before(pair.getSecond());
    }
    for (Pair<Keyword, Keyword> pair : g.findKeywordPairs("[", "]")) {
        cfg.setNoSpace().after(pair.getFirst());
        cfg.setNoSpace().before(pair.getSecond());
    }
    for (Pair<Keyword, Keyword> pair : g.findKeywordPairs("<", ">")) {
        cfg.setNoSpace().after(pair.getFirst());
        cfg.setNoSpace().before(pair.getSecond());
    }
    for (Keyword comma : g.findKeywords(",")) {
        cfg.setNoSpace().before(comma);
    }
    for (Pair<Keyword, Keyword> pair : g.findKeywordPairs(":", ";")) {
        cfg.setNoSpace().before(pair.getFirst());
        cfg.setNoSpace().before(pair.getSecond());
        cfg.setLinewrap().after(pair.getFirst());
        cfg.setLinewrap().after(pair.getSecond());
        cfg.setIndentation(pair.getFirst(), pair.getSecond());
        cfg.setLinewrap(0, 0, 1).range(pair.getFirst(), pair.getSecond());
    }
    // Grammar
    GrammarElements gr = g.getGrammarAccess();
    cfg.setNoLinewrap().between(gr.getWithKeyword_2_0(), gr.getUsedGrammarsAssignment_2_1());
    cfg.setNoSpace().between(gr.getDefinesHiddenTokensAssignment_3_0(), gr.getLeftParenthesisKeyword_3_1());
    cfg.setLinewrap(2).between(gr.getNameAssignment_1(), gr.getMetamodelDeclarationsAssignment_4());
    cfg.setLinewrap(2).between(gr.getGroup_2(), gr.getMetamodelDeclarationsAssignment_4());
    cfg.setLinewrap(2).between(gr.getGroup_3(), gr.getMetamodelDeclarationsAssignment_4());
    cfg.setLinewrap().after(gr.getMetamodelDeclarationsAssignment_4());
    cfg.setLinewrap(2).between(gr.getMetamodelDeclarationsAssignment_4(), gr.getRulesAssignment_5());
    cfg.setLinewrap(2).before(gr.getRulesAssignment_5());
    // ParserRule
    ParserRuleElements pr = g.getParserRuleAccess();
    cfg.setNoSpace().before(pr.getLeftParenthesisKeyword_2_1());
    // TypeRef
    TypeRefElements typeRef = g.getTypeRefAccess();
    cfg.setNoSpace().around(typeRef.getColonColonKeyword_0_1());
    // UnorderedGroup
    UnorderedGroupElements uge = g.getUnorderedGroupAccess();
    cfg.setNoSpace().around(uge.getUnorderedGroupElementsAction_1_0());
    // AbstractToken
    AbstractTokenWithCardinalityElements at = g.getAbstractTokenWithCardinalityAccess();
    cfg.setNoSpace().before(at.getCardinalityAsteriskKeyword_1_0_1());
    cfg.setNoSpace().before(at.getCardinalityPlusSignKeyword_1_0_2());
    cfg.setNoSpace().before(at.getCardinalityQuestionMarkKeyword_1_0_0());
    // Action
    ActionElements ac = g.getActionAccess();
    cfg.setNoSpace().around(ac.getOperatorAssignment_2_2());
    cfg.setNoSpace().around(ac.getFullStopKeyword_2_0());
    cfg.setNoSpace().after(ac.getLeftCurlyBracketKeyword_0());
    cfg.setNoSpace().before(ac.getRightCurlyBracketKeyword_3());
    // Assignment
    AssignmentElements as = g.getAssignmentAccess();
    cfg.setNoSpace().around(as.getOperatorAssignment_2());
    // CrossReference
    CrossReferenceElements cr = g.getCrossReferenceAccess();
    cfg.setNoSpace().around(cr.getVerticalLineKeyword_2_0());
    // TerminalToken
    TerminalTokenElements tt = g.getTerminalTokenAccess();
    cfg.setNoSpace().before(tt.getCardinalityAssignment_1());
    // NegatedToken
    NegatedTokenElements ne = g.getNegatedTokenAccess();
    cfg.setNoSpace().after(ne.getExclamationMarkKeyword_0());
    // UntilToken
    UntilTokenElements ut = g.getUntilTokenAccess();
    cfg.setNoSpace().around(ut.getHyphenMinusGreaterThanSignKeyword_0());
    // CharacterRange
    CharacterRangeElements cre = g.getCharacterRangeAccess();
    cfg.setNoSpace().around(cre.getFullStopFullStopKeyword_1_1());
    // EnumLiteralDeclaration
    EnumLiteralDeclarationElements eld = g.getEnumLiteralDeclarationAccess();
    cfg.setNoSpace().around(eld.getEqualsSignKeyword_1_0());
    // GuardCondition
    NegationElements na = g.getNegationAccess();
    cfg.setNoSpace().after(na.getExclamationMarkKeyword_1_1());
    // RuleCall
    RuleCallElements rca = g.getRuleCallAccess();
    cfg.setNoSpace().before(rca.getLessThanSignKeyword_1_0());
    // NamedArgument
    NamedArgumentElements naa = g.getNamedArgumentAccess();
    cfg.setNoSpace().around(naa.getCalledByNameAssignment_0_1());
    cfg.setNoSpace().around(naa.getValueAssignment_1());
    cfg.setNoSpace().around(naa.getParameterAssignment_0_0());
    // @Override
    AnnotationElements a = g.getAnnotationAccess();
    cfg.setNoSpace().between(a.getCommercialAtKeyword_0(), a.getNameAssignment_1());
    cfg.setLinewrap().after(g.getAnnotationRule());
    cfg.setLinewrap(2).before(g.getAnnotationRule());
// saveDebugGraphvizDiagram("XtextFormatting.dot");
}
Also used : AnnotationElements(org.eclipse.xtext.services.XtextGrammarAccess.AnnotationElements) Keyword(org.eclipse.xtext.Keyword) ParserRuleElements(org.eclipse.xtext.services.XtextGrammarAccess.ParserRuleElements) CharacterRangeElements(org.eclipse.xtext.services.XtextGrammarAccess.CharacterRangeElements) NamedArgumentElements(org.eclipse.xtext.services.XtextGrammarAccess.NamedArgumentElements) TypeRefElements(org.eclipse.xtext.services.XtextGrammarAccess.TypeRefElements) AbstractTokenWithCardinalityElements(org.eclipse.xtext.services.XtextGrammarAccess.AbstractTokenWithCardinalityElements) XtextGrammarAccess(org.eclipse.xtext.services.XtextGrammarAccess) UnorderedGroupElements(org.eclipse.xtext.services.XtextGrammarAccess.UnorderedGroupElements) ActionElements(org.eclipse.xtext.services.XtextGrammarAccess.ActionElements) EnumLiteralDeclarationElements(org.eclipse.xtext.services.XtextGrammarAccess.EnumLiteralDeclarationElements) RuleCallElements(org.eclipse.xtext.services.XtextGrammarAccess.RuleCallElements) GrammarElements(org.eclipse.xtext.services.XtextGrammarAccess.GrammarElements) CrossReferenceElements(org.eclipse.xtext.services.XtextGrammarAccess.CrossReferenceElements) AssignmentElements(org.eclipse.xtext.services.XtextGrammarAccess.AssignmentElements) NegatedTokenElements(org.eclipse.xtext.services.XtextGrammarAccess.NegatedTokenElements) NegationElements(org.eclipse.xtext.services.XtextGrammarAccess.NegationElements) TerminalTokenElements(org.eclipse.xtext.services.XtextGrammarAccess.TerminalTokenElements) UntilTokenElements(org.eclipse.xtext.services.XtextGrammarAccess.UntilTokenElements)

Aggregations

Keyword (org.eclipse.xtext.Keyword)67 EObject (org.eclipse.emf.ecore.EObject)15 RuleCall (org.eclipse.xtext.RuleCall)15 ILeafNode (org.eclipse.xtext.nodemodel.ILeafNode)14 INode (org.eclipse.xtext.nodemodel.INode)13 AbstractElement (org.eclipse.xtext.AbstractElement)9 AbstractRule (org.eclipse.xtext.AbstractRule)9 ICompositeNode (org.eclipse.xtext.nodemodel.ICompositeNode)9 Test (org.junit.Test)9 Grammar (org.eclipse.xtext.Grammar)8 ParserRule (org.eclipse.xtext.ParserRule)8 Action (org.eclipse.xtext.Action)7 CrossReference (org.eclipse.xtext.CrossReference)7 Assignment (org.eclipse.xtext.Assignment)6 EnumLiteralDeclaration (org.eclipse.xtext.EnumLiteralDeclaration)6 EnumRule (org.eclipse.xtext.EnumRule)6 Alternatives (org.eclipse.xtext.Alternatives)5 ArrayList (java.util.ArrayList)4 ENotificationImpl (org.eclipse.emf.ecore.impl.ENotificationImpl)4 TerminalRule (org.eclipse.xtext.TerminalRule)4