Java 类org.eclipse.xtext.GrammarUtil 实例源码

项目:n4js    文件:StableOrderSyntacticSequencerPDAProvider.java   
/**
 * Extracts the grammar from this transition or the NFA if this transition does not point to an
 * {@link AbstractElement}.
 */
private Grammar getGrammar(Nfa<ISynState> nfa) {
    AbstractElement grammarElement = getGrammarElement();
    if (grammarElement == null) {
        grammarElement = nfa.getStart().getGrammarElement();
        if (grammarElement == null) {
            grammarElement = nfa.getStop().getGrammarElement();
            if (grammarElement == null) {
                Iterator<ISynState> iter = nfa.getStart().getFollowers().iterator();
                while (grammarElement == null && iter.hasNext()) {
                    grammarElement = iter.next().getGrammarElement();
                }
            }
        }
    }
    Grammar grammar = GrammarUtil.getGrammar(grammarElement);
    return grammar;
}
项目:n4js    文件:UnicodeGrammarAccess.java   
@Inject
public UnicodeGrammarAccess(GrammarProvider grammarProvider) {
    this.grammar = internalFindGrammar(grammarProvider);
    this.tHEX_DIGIT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.HEX_DIGIT");
    this.tDECIMAL_INTEGER_LITERAL_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.DECIMAL_INTEGER_LITERAL_FRAGMENT");
    this.tDECIMAL_DIGIT_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.DECIMAL_DIGIT_FRAGMENT");
    this.tZWJ = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.ZWJ");
    this.tZWNJ = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.ZWNJ");
    this.tBOM = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.BOM");
    this.tWHITESPACE_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.WHITESPACE_FRAGMENT");
    this.tLINE_TERMINATOR_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.LINE_TERMINATOR_FRAGMENT");
    this.tLINE_TERMINATOR_SEQUENCE_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.LINE_TERMINATOR_SEQUENCE_FRAGMENT");
    this.tSL_COMMENT_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.SL_COMMENT_FRAGMENT");
    this.tML_COMMENT_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.ML_COMMENT_FRAGMENT");
    this.tUNICODE_COMBINING_MARK_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.UNICODE_COMBINING_MARK_FRAGMENT");
    this.tUNICODE_DIGIT_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.UNICODE_DIGIT_FRAGMENT");
    this.tUNICODE_CONNECTOR_PUNCTUATION_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.UNICODE_CONNECTOR_PUNCTUATION_FRAGMENT");
    this.tUNICODE_LETTER_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.UNICODE_LETTER_FRAGMENT");
    this.tUNICODE_SPACE_SEPARATOR_FRAGMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.UNICODE_SPACE_SEPARATOR_FRAGMENT");
    this.tANY_OTHER = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.common.unicode.Unicode.ANY_OTHER");
}
项目:n4js    文件:PatchedFollowElementComputer.java   
@Override
public void collectAbstractElements(Grammar grammar, EStructuralFeature feature,
        IFollowElementAcceptor followElementAcceptor) {
    for (Grammar superGrammar : grammar.getUsedGrammars()) {
        collectAbstractElements(superGrammar, feature, followElementAcceptor);
    }
    EClass declarator = feature.getEContainingClass();
    for (ParserRule rule : GrammarUtil.allParserRules(grammar)) {
        for (Assignment assignment : GrammarUtil.containedAssignments(rule)) {
            if (assignment.getFeature().equals(feature.getName())) {
                EClassifier classifier = GrammarUtil.findCurrentType(assignment);
                EClassifier compType = EcoreUtil2.getCompatibleType(declarator, classifier);
                if (compType == declarator) {
                    followElementAcceptor.accept(assignment);
                }
            }
        }
    }
}
项目:n4js    文件:TokenTypeRewriter.java   
private static void rewriteTypeReferences(N4JSGrammarAccess ga,
        ImmutableMap.Builder<AbstractElement, Integer> builder) {
    for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) {
        for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) {
            if (obj instanceof Assignment) {
                Assignment assignment = (Assignment) obj;
                AbstractElement terminal = assignment.getTerminal();
                if (terminal instanceof RuleCall) {
                    AbstractRule calledRule = ((RuleCall) terminal).getRule();
                    EClassifier classifier = calledRule.getType().getClassifier();
                    if (classifier instanceof EClass
                            && TypeRefsPackage.Literals.TYPE_REF.isSuperTypeOf((EClass) classifier)) {
                        builder.put(assignment, TYPE_REF_TOKEN);
                    }
                }
            }
        }
    }
}
项目:n4js    文件:TokenTypeRewriter.java   
private static void rewriteIdentifiers(N4JSGrammarAccess ga,
        ImmutableMap.Builder<AbstractElement, Integer> builder) {
    ImmutableSet<AbstractRule> identifierRules = ImmutableSet.of(
            ga.getBindingIdentifierRule(),
            ga.getIdentifierNameRule(),
            ga.getIDENTIFIERRule());
    for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) {
        for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) {
            if (obj instanceof Assignment) {
                Assignment assignment = (Assignment) obj;
                AbstractElement terminal = assignment.getTerminal();
                int type = InternalN4JSParser.RULE_IDENTIFIER;
                if (terminal instanceof CrossReference) {
                    terminal = ((CrossReference) terminal).getTerminal();
                    type = IDENTIFIER_REF_TOKEN;
                }
                if (terminal instanceof RuleCall) {
                    AbstractRule calledRule = ((RuleCall) terminal).getRule();
                    if (identifierRules.contains(calledRule)) {
                        builder.put(assignment, type);
                    }
                }
            }
        }
    }
}
项目:n4js    文件:TokenTypeRewriter.java   
private static void rewriteNumberLiterals(N4JSGrammarAccess ga,
        ImmutableMap.Builder<AbstractElement, Integer> builder) {
    for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) {
        for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) {
            if (obj instanceof Assignment) {
                Assignment assignment = (Assignment) obj;
                AbstractElement terminal = assignment.getTerminal();
                if (terminal instanceof RuleCall) {
                    AbstractRule calledRule = ((RuleCall) terminal).getRule();
                    EClassifier classifier = calledRule.getType().getClassifier();
                    if (classifier == EcorePackage.Literals.EBIG_DECIMAL) {
                        builder.put(assignment, NUMBER_LITERAL_TOKEN);
                    }
                }
            }
        }
    }
}
项目:gw4e.project    文件:DSLPoliciesGrammarAccess.java   
@Inject
public DSLPoliciesGrammarAccess(GrammarProvider grammarProvider,
        XbaseGrammarAccess gaXbase,
        XtypeGrammarAccess gaXtype) {
    this.grammar = internalFindGrammar(grammarProvider);
    this.gaXbase = gaXbase;
    this.gaXtype = gaXtype;
    this.pModel = new ModelElements();
    this.tSEV = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "gw4e.eclipse.dsl.DSLPolicies.SEV");
    this.tFORMAT_COMMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "gw4e.eclipse.dsl.DSLPolicies.FORMAT_COMMENT");
    this.tNEWLINE = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "gw4e.eclipse.dsl.DSLPolicies.NEWLINE");
    this.pComment = new CommentElements();
    this.pGraphPolicies = new GraphPoliciesElements();
    this.pModelName = new ModelNameElements();
    this.pSeverity = new SeverityElements();
    this.pPolicies = new PoliciesElements();
    this.pPathGeneratorStopCondition = new PathGeneratorStopConditionElements();
    this.pAlgorithmType = new AlgorithmTypeElements();
    this.pIntegerStopCondition = new IntegerStopConditionElements();
    this.pPercentageCondition = new PercentageConditionElements();
    this.pStringCondition = new StringConditionElements();
    this.pPercent = new PercentElements();
    this.pGraphElement = new GraphElementElements();
}
项目:org.xtext.dsl.restaurante    文件:RestauranteGrammarAccess.java   
@Inject
public RestauranteGrammarAccess(GrammarProvider grammarProvider,
        TerminalsGrammarAccess gaTerminals) {
    this.grammar = internalFindGrammar(grammarProvider);
    this.gaTerminals = gaTerminals;
    this.pRestaurante = new RestauranteElements();
    this.pIngrediente = new IngredienteElements();
    this.pProducto = new ProductoElements();
    this.pPrincipal = new PrincipalElements();
    this.pComplemento = new ComplementoElements();
    this.pBebida = new BebidaElements();
    this.pBebidaFria = new BebidaFriaElements();
    this.pBebidaCaliente = new BebidaCalienteElements();
    this.pPostre = new PostreElements();
    this.pNutricional = new NutricionalElements();
    this.pMenu = new MenuElements();
    this.pProductoY = new ProductoYElements();
    this.pProductoO = new ProductoOElements();
    this.pFloat = new FloatElements();
    this.eSalsaRecomendada = new SalsaRecomendadaElements();
    this.eTamanioMenu = new TamanioMenuElements();
    this.eDistribuidor = new DistribuidorElements();
    this.tFECHA = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.dsl.restaurante.Restaurante.FECHA");
    this.tURL = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.xtext.dsl.restaurante.Restaurante.URL");
}
项目:dsl-devkit    文件:CheckHighlightingCalculator.java   
@Override
protected void highlightSpecialIdentifiers(final IHighlightedPositionAcceptor acceptor, final ICompositeNode root) {
  TerminalRule idRule = grammarAccess.getIDRule();

  for (ILeafNode leaf : root.getLeafNodes()) {
    if (commentProvider.isJavaDocComment(leaf)) {
      // not really a special identifier, but we don't want to iterate over the leaf nodes twice, do we?
      acceptor.addPosition(leaf.getOffset(), leaf.getLength(), CheckHighlightingConfiguration.JAVADOC_ID);
    } else if (!leaf.isHidden()) {
      if (leaf.getGrammarElement() instanceof Keyword) {
        // Check if it is a keyword used as an identifier.
        ParserRule rule = GrammarUtil.containingParserRule(leaf.getGrammarElement());
        if (FEATURE_CALL_ID_RULE_NAME.equals(rule.getName())) {
          acceptor.addPosition(leaf.getOffset(), leaf.getLength(), DefaultHighlightingConfiguration.DEFAULT_ID);
        }
      } else {
        highlightSpecialIdentifiers(leaf, acceptor, idRule);
      }
    }
  }
}
项目:xtext-extras    文件:BrokenConstructorCallAwareEObjectAtOffsetHelper.java   
@Override
protected EObject resolveCrossReferencedElement(INode node) {
    EObject referenceOwner = NodeModelUtils.findActualSemanticObjectFor(node);
    if (referenceOwner != null) {
        EReference crossReference = GrammarUtil.getReference((CrossReference) node.getGrammarElement(),
                referenceOwner.eClass());
        if (!crossReference.isMany()) {
            EObject resultOrProxy = (EObject) referenceOwner.eGet(crossReference);
            if (resultOrProxy != null && resultOrProxy.eIsProxy() && crossReference == XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR) {
                if (referenceOwner instanceof XConstructorCall) {
                    JvmIdentifiableElement linkedType = batchTypeResolver.resolveTypes(referenceOwner).getLinkedFeature((XConstructorCall)referenceOwner);
                    if (linkedType != null)
                        return linkedType;
                }
            } 
            return resultOrProxy;
        } else {
            return super.resolveCrossReferencedElement(node);
        }
    }
    return null;
}
项目:xtext-core    文件:CrossReferenceSerializer.java   
@Override
public boolean isValid(EObject semanticObject, CrossReference crossref, EObject target, INode node, Acceptor errors) {
    if ((target == null || target.eIsProxy()) && node != null) {
        CrossReference crossrefFromNode = GrammarUtil.containingCrossReference(node.getGrammarElement());
        return crossref == crossrefFromNode;
    }

    final EReference ref = GrammarUtil.getReference(crossref, semanticObject.eClass());
    final IScope scope = scopeProvider.getScope(semanticObject, ref);
    if (scope == null) {
        if (errors != null)
            errors.accept(diagnostics.getNoScopeFoundDiagnostic(semanticObject, crossref, target));
        return false;
    }

    if (target != null && target.eIsProxy()) {
        target = handleProxy(target, semanticObject, ref);
    }

    return getCrossReferenceNameFromScope(semanticObject, crossref, target, scope, errors) != null;
}
项目:xtext-core    文件:Xtext2EcoreTransformer.java   
private boolean checkDatatypeRules() {
    boolean result = true;
    for (AbstractRule rule : grammar.getRules()) {
        try {
            if (rule instanceof ParserRule && GrammarUtil.isDatatypeRule((ParserRule) rule) && !DatatypeRuleUtil.isValidDatatypeRule((ParserRule) rule)) {
                throw new TransformationException(TransformationErrorCode.InvalidDatatypeRule,
                        "Datatype rules may only use other datatype rules, lexer rules and keywords.", rule);
            }
        }
        catch (TransformationException e) {
            reportError(e);
            result = false;
        }
    }
    return result;
}
项目:xtext-core    文件:FollowElementComputer.java   
public void collectAbstractElements(Grammar grammar, EStructuralFeature feature, IFollowElementAcceptor followElementAcceptor) {
    for (Grammar superGrammar : grammar.getUsedGrammars()) {
        collectAbstractElements(superGrammar, feature, followElementAcceptor);
    }
    EClass declarator = feature.getEContainingClass();
    for (ParserRule rule : GrammarUtil.allParserRules(grammar)) {
        for (Assignment assignment : GrammarUtil.containedAssignments(rule)) {
            if (assignment.getFeature().equals(feature.getName())) {
                EClassifier classifier = GrammarUtil.findCurrentType(assignment);
                EClassifier compType = EcoreUtil2.getCompatibleType(declarator, classifier);
                if (compType == declarator) {
                    followElementAcceptor.accept(assignment);
                }
            }
        }
    }
}
项目:xtext-core    文件:RequiredRuleNameComputer.java   
protected String adjustRuleName(String ruleName, Param param) {
    AbstractElement elementToParse = param.elementToParse;
    Set<Parameter> context = getAssignedParameters(elementToParse, param.paramStack);
    if (!context.isEmpty()) {
        ParserRule containingRule = GrammarUtil.containingParserRule(elementToParse);
        String antlrRuleName = ruleNames.getAntlrRuleName(containingRule);
        int len = antlrRuleName.length();
        if (antlrRuleName.startsWith("rule")) {
            len += 2; // rule__XYZ instead of ruleXYZ
        }
        int config = getParameterConfig(context);
        String result = ruleNames.getAntlrRuleName(containingRule, config) + ruleName.substring(len);
        return result;
    }
    return ruleName;
}
项目:xtext-core    文件:OverriddenValueInspectorTest.java   
@Test
public void testAssignedAction_02() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("First : Second ({First.second=current} name=ID)*;");
  _builder.newLine();
  _builder.append("Second: name=ID;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "First");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertTrue(this.warnings.toString(), this.warnings.isEmpty());
}
项目:xtext-core    文件:Xtext2EcoreTransformer.java   
private EClassifierInfo findOrCreateEClassifierInfo(TypeRef typeRef, String name, boolean createIfMissing) throws TransformationException {
    if (typeRef.getClassifier() != null && typeRef.getMetamodel() == null)
        throw new TransformationException(TransformationErrorCode.UnknownMetaModelAlias,
                "Cannot find EPackage for type '" + typeRef.getClassifier().getName() + "'", typeRef);
    EClassifierInfo info = eClassifierInfos.getInfo(typeRef);
    if (info == null) {
        // we assumend EString for terminal rules and datatype rules, so
        // we have to do a look up in super grammar
        EDataType dataType = GrammarUtil.findEString(GrammarUtil.getGrammar(typeRef));
        if (dataType != null && typeRef.getClassifier() == dataType) {
            info = eClassifierInfos.getInfoOrNull(typeRef);
            if (info != null)
                return info;
        }
        if (createIfMissing)
            info = createEClassifierInfo(typeRef, name);
    }
    return info;
}
项目:xtext-core    文件:KeywordBasedValueConverter.java   
/**
 * @throws IllegalArgumentException if the rule is not a datatype rule or does not fulfill
 *   the pattern <pre>RuleName: 'keyword' | 'other';</pre>
 */
@Override
public void setRule(AbstractRule rule) {
    this.rule = rule;
    if (!GrammarUtil.isDatatypeRule(rule))
        throw new IllegalArgumentException(rule.getName() + " is not a data type rule");
    if (!(rule.getAlternatives() instanceof Alternatives) && !(rule.getAlternatives() instanceof Keyword)) {
        throw new IllegalArgumentException(rule.getName() + " is not a simple keyword nor an alternative");
    }
    if (rule.getAlternatives() instanceof Keyword) {
        keywords = ImmutableSet.of(keywordToString((Keyword) rule.getAlternatives()));
    } else {
        Alternatives alternatives = (Alternatives) rule.getAlternatives();
        ImmutableSet.Builder<String> builder = ImmutableSet.builder();
        for(AbstractElement element: alternatives.getElements()) {
            if (!(element instanceof Keyword)) {
                throw new IllegalArgumentException(rule.getName() + "'s body does not contain an alternative of keywords");
            }
            builder.add(keywordToString((Keyword) element));
        }
        keywords = builder.build();
    }
}
项目:xtext-core    文件:GrammarAccessFragment2.java   
protected StringConcatenationClient _initializer(final TerminalRule it) {
  StringConcatenationClient _client = new StringConcatenationClient() {
    @Override
    protected void appendTo(StringConcatenationClient.TargetStringConcatenation _builder) {
      _builder.append("this.");
      String _gaRuleAccessorLocalVarName = GrammarAccessFragment2.this.gaRuleAccessorLocalVarName(it);
      _builder.append(_gaRuleAccessorLocalVarName);
      _builder.append(" = (");
      _builder.append(TerminalRule.class);
      _builder.append(") ");
      _builder.append(GrammarUtil.class);
      _builder.append(".findRuleForName(getGrammar(), \"");
      String _qualifiedName = GrammarAccessFragment2.this.getQualifiedName(it);
      _builder.append(_qualifiedName);
      _builder.append("\");");
      _builder.newLineIfNotEmpty();
    }
  };
  return _client;
}
项目:xtext-core    文件:OverriddenValueInspectorTest.java   
@Test
public void testOptionalAction_01() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("First : Second ({First.second=current} id=INT)? name=ID;");
  _builder.newLine();
  _builder.append("Second: \'keyword\' name=ID;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "First");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertEquals(this.warnings.toString(), 2, this.warnings.size());
}
项目:xtext-core    文件:FlattenedGrammarAccess.java   
public FlattenedGrammarAccess(final RuleNames names, final RuleFilter filter) {
  final Grammar grammar = names.getContextGrammar();
  Grammar flattenedGrammar = this.<Grammar>copy(grammar);
  flattenedGrammar.setName(grammar.getName());
  LinkedHashMap<RuleWithParameterValues, AbstractRule> origToCopy = Maps.<RuleWithParameterValues, AbstractRule>newLinkedHashMap();
  final ArrayList<AbstractRule> copies = this.copyRuleStubs(names, origToCopy, filter.getRules(grammar), filter.isDiscardRuleTypeRef());
  EList<AbstractRule> _rules = flattenedGrammar.getRules();
  Iterables.<AbstractRule>addAll(_rules, copies);
  Multimap<TerminalRule, AbstractRule> calledFrom = this.copyRuleBodies(copies, origToCopy);
  this.setHiddenTokens(flattenedGrammar, grammar, origToCopy);
  this.markAsFragment(calledFrom);
  boolean _isDiscardUnreachableRules = filter.isDiscardUnreachableRules();
  if (_isDiscardUnreachableRules) {
    Set<AbstractRule> usedRules = CollectionLiterals.<AbstractRule>newHashSet();
    boolean _isDiscardTerminalRules = filter.isDiscardTerminalRules();
    boolean _not = (!_isDiscardTerminalRules);
    if (_not) {
      usedRules.addAll(GrammarUtil.allTerminalRules(flattenedGrammar));
    }
    UsedRulesFinder finder = new UsedRulesFinder(usedRules);
    finder.compute(flattenedGrammar);
    flattenedGrammar.getRules().retainAll(usedRules);
  }
  this.flattenedGrammar = flattenedGrammar;
  new OriginalGrammar(grammar).attachToEmfObject(flattenedGrammar);
}
项目:xtext-core    文件:OverriddenValueInspectorTest.java   
@Test
public void testBug306281_04() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("Model : name=ID (({Binary.left=current} operator = \'-\' | {Binary.left=current} operator = \'+\')? name=ID);");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "Model");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertEquals(this.warnings.toString(), 2, this.warnings.size());
}
项目:xtext-core    文件:OverriddenValueInspectorTest.java   
@Test
public void testBug306281_11() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("Model returns Model: SubModel ({Binary.params+=current} operator =\'+\' params+=SubModel)*;");
  _builder.newLine();
  _builder.append("SubModel returns Model: \'(\'Model\')\';");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "Model");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertTrue(this.warnings.toString(), this.warnings.isEmpty());
}
项目:xtext-core    文件:GrammarPDAProvider.java   
@Override
public SerializationContextMap<Pda<ISerState, RuleCall>> getGrammarPDAs(Grammar grammar) {
    RuleNames names = RuleNames.getRuleNames(grammar, true);
    RuleFilter filter = new RuleFilter();
    filter.setDiscardTerminalRules(true);
    filter.setDiscardUnreachableRules(false);
    filter.setDiscardRuleTypeRef(false);
    Grammar flattened = new FlattenedGrammarAccess(names, filter).getFlattenedGrammar();
    Builder<Pda<ISerState, RuleCall>> result = SerializationContextMap.<Pda<ISerState, RuleCall>>builder();
    for (ParserRule rule : GrammarUtil.allParserRules(flattened)) {
        RuleWithParameterValues withParams = RuleWithParameterValues.findInEmfObject(rule);
        AbstractRule original = withParams.getOriginal();
        if (original instanceof ParserRule && isValidRule((ParserRule) original)) {
            ISerializationContext context = createContext((ParserRule) original, withParams.getParamValues());
            try {
                Pda<ISerState, RuleCall> pda = createPDA(grammar, rule);
                result.put(context, pda);
            } catch (Exception e) {
                LOG.error("Error creating PDA for context '" + context + "': " + e.getMessage(), e);
            }
        }
    }
    return result.create();
}
项目:xtext-core    文件:GrammarPDAProviderTest.java   
private void assertNoLeakedGrammarElements(final Grammar grammar, final Pda<ISerState, RuleCall> pda) {
  final Function1<ISerState, AbstractElement> _function = (ISerState it) -> {
    return it.getGrammarElement();
  };
  Iterable<AbstractElement> _filterNull = IterableExtensions.<AbstractElement>filterNull(IterableExtensions.<ISerState, AbstractElement>map(new NfaUtil().<ISerState>collect(pda), _function));
  for (final AbstractElement ele : _filterNull) {
    {
      final Grammar actual = GrammarUtil.getGrammar(ele);
      if ((actual != grammar)) {
        String _objPath = EmfFormatter.objPath(ele);
        String _plus = ("Element " + _objPath);
        String _plus_1 = (_plus + " leaked!");
        Assert.fail(_plus_1);
      }
    }
  }
}
项目:xtext-core    文件:XtextLinkingService.java   
private List<EObject> getPackage(ReferencedMetamodel context, ILeafNode text) {
    String nsUri = getMetamodelNsURI(text);
    if (nsUri == null)
        return Collections.emptyList();
    Grammar grammar = GrammarUtil.getGrammar(context);
    Set<Grammar> visitedGrammars = new HashSet<Grammar>();
    for (Grammar usedGrammar: grammar.getUsedGrammars()) {
        List<EObject> result = getPackage(nsUri, usedGrammar, visitedGrammars);
        if (result != null)
            return result;
    }
    QualifiedName packageNsURI = QualifiedName.create(nsUri);
    EPackage pack = findPackageInScope(context, packageNsURI);
    if (pack == null) {
        pack = findPackageInAllDescriptions(context, packageNsURI);
        if (pack == null) {
            pack = loadEPackage(nsUri, context.eResource().getResourceSet());
        }
    }
    if (pack != null)
        return Collections.<EObject>singletonList(pack);
    return Collections.emptyList();
}
项目:xtext-core    文件:OverriddenValueInspectorTest.java   
@Test
public void testBug280011_01() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("Q : \'x\' a = ID | \'y\' a = ID ;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "Q");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertTrue(this.warnings.toString(), this.warnings.isEmpty());
}
项目:xtext-core    文件:IdeaPluginGenerator.java   
protected Iterable<AbstractElement> getEObjectElements(final AbstractRule rule) {
  final Function1<AbstractElement, Boolean> _function = (AbstractElement element) -> {
    boolean _switchResult = false;
    boolean _matched = false;
    if (element instanceof Action) {
      _matched=true;
    }
    if (!_matched) {
      if (element instanceof RuleCall) {
        boolean _isEObjectRuleCall = GrammarUtil.isEObjectRuleCall(element);
        if (_isEObjectRuleCall) {
          _matched=true;
        }
      }
    }
    if (_matched) {
      _switchResult = true;
    }
    if (!_matched) {
      _switchResult = false;
    }
    return Boolean.valueOf(_switchResult);
  };
  return IterableExtensions.<AbstractElement>filter(EcoreUtil2.<AbstractElement>eAllOfType(rule, AbstractElement.class), _function);
}
项目:xtext-core    文件:OverriddenValueInspectorTest.java   
@Test
public void testRuleCall_01() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("First returns Object: (Third|Second) cardinality=(\'+\'|\'*\')?;");
  _builder.newLine();
  _builder.append("Second returns Object: \'(\' First \')\';");
  _builder.newLine();
  _builder.append("Third returns Object: name=ID;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "First");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertEquals(this.warnings.toString(), 2, this.warnings.size());
}
项目:xtext-core    文件:TerminalRuleTestLanguageConverters.java   
@ValueConverter(rule = "ID")
public IValueConverter<String> ID() {
    return new AbstractNullSafeConverter<String>() {
        @Override
        protected String internalToValue(String string, INode node) {
            return string.startsWith("^") ? string.substring(1) : string;
        }

        @Override
        protected String internalToString(String value) {
            if (GrammarUtil.getAllKeywords(getGrammar()).contains(value)) {
                return "^"+value;
            }
            return value;
        }
    };
}
项目:xtext-core    文件:OverriddenValueInspectorTest.java   
@Test
public void testUnassignedRule_04() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("First : Second (name=ID)? id=INT;");
  _builder.newLine();
  _builder.append("Second: id=INT (name=ID)?;");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "First");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertEquals(this.warnings.toString(), 4, this.warnings.size());
}
项目:xtext-core    文件:GrammarUtilTest.java   
@Test
public void testFindCurrentType_04() throws Exception {
  this.with(XtextStandaloneSetup.class);
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar myLang with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate g \'http://1\'");
  _builder.newLine();
  _builder.append("Rule:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("Fragment;");
  _builder.newLine();
  _builder.append("fragment Fragment: name=ID SecondFragment?;");
  _builder.newLine();
  _builder.append("fragment SecondFragment: {SubRule.named=current} value=ID;");
  _builder.newLine();
  String model = _builder.toString();
  final XtextResource r = this.getResourceFromString(model);
  EObject _get = r.getContents().get(0);
  final Grammar grammar = ((Grammar) _get);
  final AbstractRule rule = IterableExtensions.<AbstractRule>head(grammar.getRules());
  final AbstractElement fragmentCall = rule.getAlternatives();
  final EClassifier currentType = GrammarUtil.findCurrentType(fragmentCall);
  Assert.assertEquals("Rule", currentType.getName());
}
项目:n4js    文件:GrammarLinter.java   
private void printKeywordsOnlyInDatatypeRules() {
    Grammar grammar = grammarAccess.getGrammar();
    ListMultimap<String, Keyword> allKeywords = getAllKeywords(grammar);
    System.out.println("Keywords which do not occur in production rules: ");
    outer: for (Collection<Keyword> chunk : allKeywords.asMap().values()) {
        for (Keyword keyword : chunk) {
            AbstractRule rule = EcoreUtil2.getContainerOfType(keyword, AbstractRule.class);
            if (!GrammarUtil.isDatatypeRule(rule)) {
                continue outer;
            }
        }
        System.out.println("  " + ((List<Keyword>) chunk).get(0).getValue());
    }
    System.out.println();
}
项目:n4js    文件:PatchedFollowElementComputer.java   
private boolean isAlternativeWithEmptyPath(AbstractElement abstractElement) {
    if (abstractElement instanceof Alternatives) {
        Alternatives alternatives = (Alternatives) abstractElement;
        for (AbstractElement path : alternatives.getElements()) {
            if (GrammarUtil.isOptionalCardinality(path))
                return true;
        }
    }
    return false;
}
项目:n4js    文件:N4JSLinker.java   
/**
 * Installs proxies for all non containment references and only if the node representing the EObject that contains
 * the cross reference has got leaf nodes (as a leaf node represents the cross reference).
 *
 * @param resource
 *            the N4JSResource
 * @param obj
 *            the EObject containing the cross reference
 * @param producer
 *            the error/warning producer
 * @param parentNode
 *            the node representing obj inside the node model
 */
private void installProxies(N4JSResource resource, EObject obj, IDiagnosticProducer producer,
        ICompositeNode parentNode, boolean dontCheckParent) {
    final EClass eClass = obj.eClass();
    if (eClass.getEAllReferences().size() - eClass.getEAllContainments().size() == 0)
        return;

    for (INode node = parentNode.getFirstChild(); node != null; node = node.getNextSibling()) {
        EObject grammarElement = node.getGrammarElement();
        if (grammarElement instanceof CrossReference && hasLeafNodes(node)) {
            producer.setNode(node);
            CrossReference crossReference = (CrossReference) grammarElement;
            final EReference eRef = GrammarUtil.getReference(crossReference, eClass);
            if (eRef == null) {
                ParserRule parserRule = GrammarUtil.containingParserRule(crossReference);
                final String feature = GrammarUtil.containingAssignment(crossReference).getFeature();
                throw new IllegalStateException("Couldn't find EReference for crossreference '" + eClass.getName()
                        + "::" + feature + "' in parser rule '" + parserRule.getName() + "'.");
            }
            createAndSetProxy(resource, obj, node, eRef, crossReference, producer);
            afterCreateAndSetProxy(obj, node, eRef, crossReference, producer);
        } else if (grammarElement instanceof RuleCall && node instanceof ICompositeNode) {
            RuleCall ruleCall = (RuleCall) grammarElement;
            AbstractRule calledRule = ruleCall.getRule();
            if (calledRule instanceof ParserRule && ((ParserRule) calledRule).isFragment()) {
                installProxies(resource, obj, producer, (ICompositeNode) node, true);
            }
        }
    }
    if (!dontCheckParent && shouldCheckParentNode(parentNode)) {
        installProxies(resource, obj, producer, parentNode.getParent(), dontCheckParent);
    }
}
项目:n4js    文件:N4MFGrammarAccess.java   
@Inject
public N4MFGrammarAccess(GrammarProvider grammarProvider,
        TerminalsGrammarAccess gaTerminals) {
    this.grammar = internalFindGrammar(grammarProvider);
    this.gaTerminals = gaTerminals;
    this.pProjectDescription = new ProjectDescriptionElements();
    this.eProjectType = new ProjectTypeElements();
    this.pExecModule = new ExecModuleElements();
    this.pTestedProjects = new TestedProjectsElements();
    this.pInitModules = new InitModulesElements();
    this.pImplementedProjects = new ImplementedProjectsElements();
    this.pProjectDependencies = new ProjectDependenciesElements();
    this.pProvidedRuntimeLibraries = new ProvidedRuntimeLibrariesElements();
    this.pRequiredRuntimeLibraries = new RequiredRuntimeLibrariesElements();
    this.pExtendedRuntimeEnvironment = new ExtendedRuntimeEnvironmentElements();
    this.pDeclaredVersion = new DeclaredVersionElements();
    this.pSourceFragment = new SourceFragmentElements();
    this.eSourceFragmentType = new SourceFragmentTypeElements();
    this.pModuleFilter = new ModuleFilterElements();
    this.pBootstrapModule = new BootstrapModuleElements();
    this.pModuleFilterSpecifier = new ModuleFilterSpecifierElements();
    this.eModuleFilterType = new ModuleFilterTypeElements();
    this.pProvidedRuntimeLibraryDependency = new ProvidedRuntimeLibraryDependencyElements();
    this.pRequiredRuntimeLibraryDependency = new RequiredRuntimeLibraryDependencyElements();
    this.pTestedProject = new TestedProjectElements();
    this.pProjectReference = new ProjectReferenceElements();
    this.pProjectDependency = new ProjectDependencyElements();
    this.pSimpleProjectDescription = new SimpleProjectDescriptionElements();
    this.pVersionConstraint = new VersionConstraintElements();
    this.eProjectDependencyScope = new ProjectDependencyScopeElements();
    this.eModuleLoader = new ModuleLoaderElements();
    this.pN4mfIdentifier = new N4mfIdentifierElements();
    this.tID = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.n4js.n4mf.N4MF.ID");
}
项目:gemoc-studio    文件:DslGrammarAccess.java   
@Inject
public DslGrammarAccess(GrammarProvider grammarProvider) {
    this.grammar = internalFindGrammar(grammarProvider);
    this.pDsl = new DslElements();
    this.pEntry = new EntryElements();
    this.pWORD = new WORDElements();
    this.pVALUE_WORD = new VALUE_WORDElements();
    this.tSEPARATOR = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.gemoc.Dsl.SEPARATOR");
    this.tSL_COMMENT = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.gemoc.Dsl.SL_COMMENT");
    this.tLETTER = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.gemoc.Dsl.LETTER");
    this.pMULTILINE = new MULTILINEElements();
    this.tSPACE = (TerminalRule) GrammarUtil.findRuleForName(getGrammar(), "org.eclipse.gemoc.Dsl.SPACE");
}
项目:xtext-core    文件:GrammarTest.java   
@Test public void testRuleNestedModelId() {
    AbstractRule rule = grammar.getRules().get(3);
    assertEquals("NestedModelId", rule.getName());
    ParserRule parserRule = (ParserRule) rule;
    assertTrue(GrammarUtil.isDatatypeRule(parserRule));
    assertNotNull(rule.getType());
    assertNotNull(rule.getType().getClassifier());
    assertEquals(EcorePackage.Literals.ESTRING, rule.getType().getClassifier());
}
项目:xtext-core    文件:SequenceFeeder.java   
protected void acceptKeyword(Assignment ass, Keyword keyword, Object value, String token, int index, ILeafNode node) {
    CrossReference crossRef = GrammarUtil.containingCrossReference(keyword);
    if (crossRef != null)
        sequenceAcceptor.acceptAssignedCrossRefKeyword(keyword, token, (EObject) value, index, node);
    else
        sequenceAcceptor.acceptAssignedKeyword(keyword, token, value, index, node);
}
项目:xtext-extras    文件:XbaseIdeContentProposalProvider.java   
@Override
protected void _createProposals(final RuleCall ruleCall, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) {
  AbstractRule _rule = ruleCall.getRule();
  boolean _matched = false;
  ParserRule _xExpressionRule = this._xbaseGrammarAccess.getXExpressionRule();
  if (Objects.equal(_rule, _xExpressionRule)) {
    _matched=true;
    if (((ruleCall.eContainer() instanceof Group) && Objects.equal(GrammarUtil.containingRule(ruleCall).getName(), "XParenthesizedExpression"))) {
      this.createLocalVariableAndImplicitProposals(context.getCurrentModel(), IExpressionScope.Anchor.WITHIN, context, acceptor);
    }
  }
  if (!_matched) {
    super._createProposals(ruleCall, context, acceptor);
  }
}
项目:xtext-core    文件:OverriddenValueInspectorTest.java   
@Test
public void testFragment_07() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar org.foo with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate metamodel \'foo.sample\'");
  _builder.newLine();
  _builder.append("EntryRule:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("name=ID FragmentWithAction");
  _builder.newLine();
  _builder.append(";");
  _builder.newLine();
  _builder.append("fragment FragmentWithAction returns EntryRule:");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("{EntryRule.prev=current} name=ID");
  _builder.newLine();
  _builder.append(";");
  _builder.newLine();
  String grammarAsString = _builder.toString();
  final Grammar grammar = this.getGrammar(grammarAsString);
  AbstractRule _findRuleForName = GrammarUtil.findRuleForName(grammar, "EntryRule");
  final ParserRule rule = ((ParserRule) _findRuleForName);
  this.validateRule(rule);
  Assert.assertEquals(this.warnings.toString(), 0, this.warnings.size());
  AbstractRule _findRuleForName_1 = GrammarUtil.findRuleForName(grammar, "FragmentWithAction");
  final ParserRule fragment = ((ParserRule) _findRuleForName_1);
  this.validateRule(fragment);
  Assert.assertEquals(this.warnings.toString(), 0, this.warnings.size());
}