Java Code Examples for org.eclipse.xtext.GrammarUtil#isDatatypeRule()

The following examples show how to use org.eclipse.xtext.GrammarUtil#isDatatypeRule() . 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: FormatJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Verify that only rule self directives are used for terminal, enum and data type rules.
 *
 * @param model
 *          the GrammarRule
 */
@Check
public void checkDataTypeOrEnumRule(final GrammarRule model) {
  if (model.getTargetRule() instanceof TerminalRule || model.getTargetRule() instanceof EnumRule
      || (model.getTargetRule() instanceof ParserRule && GrammarUtil.isDatatypeRule((ParserRule) model.getTargetRule()))) {
    Iterator<EObject> grammarElementAccessors = collectGrammarElementAccessors(model);
    boolean selfAccessOnly = Iterators.all(grammarElementAccessors, new Predicate<EObject>() {
      @Override
      public boolean apply(final EObject input) {
        return input instanceof GrammarElementReference && ((GrammarElementReference) input).getSelf() != null;
      }
    });
    if (!selfAccessOnly) {
      error(NLS.bind("For data type, enum or terminal rule {0} only ''rule'' directive may be used", model.getTargetRule().getName()), FormatPackage.Literals.GRAMMAR_RULE__DIRECTIVES, ILLEGAL_DIRECTIVE_CODE);
    }
  }
}
 
Example 2
Source File: SyntaxFilteredScopes.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public IScope create(IScope parent, AbstractElement syntaxElement) {
	if (syntaxElement instanceof CrossReference) {
		return create(parent, ((CrossReference) syntaxElement).getTerminal());
	}
	if (syntaxElement instanceof RuleCall) {
		AbstractRule rule = ((RuleCall) syntaxElement).getRule();
		if (GrammarUtil.isDatatypeRule(rule)) {
			List<String> values = getEnumeratedValues((ParserRule) rule);
			if (values.isEmpty()) {
				return parent;
			}
			return new SyntaxFilteredScope(parent, values);
		}
	}
	return parent;
}
 
Example 3
Source File: KeywordAlternativeConverter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @throws IllegalArgumentException if the rule is not a datatype rule or does not match
 *   the pattern <pre>RuleName: 'keyword' | 'other';</pre>
 */
@Override
public void setRule(AbstractRule rule) {
	if (!GrammarUtil.isDatatypeRule(rule))
		throw new IllegalArgumentException(rule.getName() + " is not a data type rule");
	if (!(rule.getAlternatives() instanceof Alternatives)) {
		if (rule.getAlternatives() instanceof RuleCall) {
			delegateRule = ((RuleCall) rule.getAlternatives()).getRule();
			keywords = Collections.emptySet();
			return;
		}
		throw mismatchedRuleBody(rule);
	}
	Alternatives alternatives = (Alternatives) rule.getAlternatives();
	ImmutableSet.Builder<String> builder = ImmutableSet.builder();
	for (AbstractElement element : alternatives.getElements()) {
		processElement(element, rule, builder);
	}
	keywords = builder.build();
}
 
Example 4
Source File: KeywordBasedValueConverter.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @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();
	}
}
 
Example 5
Source File: AbstractElementFinder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public List<Pair<Keyword, Keyword>> findKeywordPairs(String leftKw, String rightKw) {
	ArrayList<Pair<Keyword, Keyword>> pairs = new ArrayList<Pair<Keyword, Keyword>>();
	for (AbstractRule ar : getRules())
		if (ar instanceof ParserRule && !GrammarUtil.isDatatypeRule((ParserRule) ar)) {
			Stack<Keyword> openings = new Stack<Keyword>();
			TreeIterator<EObject> i = ar.eAllContents();
			while (i.hasNext()) {
				EObject o = i.next();
				if (o instanceof Keyword) {
					Keyword k = (Keyword) o;
					if (leftKw.equals(k.getValue()))
						openings.push(k);
					else if (rightKw.equals(k.getValue())) {
						if (openings.size() > 0)
							pairs.add(Tuples.create(openings.pop(), k));
					}
				}
			}
		}
	return pairs;
}
 
Example 6
Source File: XtextValidator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkRuleCallInUnorderedGroup(final RuleCall call) {
	if (call.getRule() == null || call.getRule().eIsProxy() || !(call.getRule() instanceof ParserRule))
		return;
	if (GrammarUtil.isDatatypeRule((ParserRule) call.getRule()))
		return;
	if (GrammarUtil.isAssigned(call))
		return;
	if (EcoreUtil2.getContainerOfType(call, UnorderedGroup.class) != null)
		error(
				"Unassigned rule calls may not be used in unordered groups.", 
				call, 
				null,
				ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
				null);
}
 
Example 7
Source File: AbstractAntlrGrammarGenerator.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected String _crossrefEbnf(final RuleCall it, final CrossReference ref, final boolean supportActions) {
  String _xblockexpression = null;
  {
    final AbstractRule rule = it.getRule();
    if ((rule instanceof ParserRule)) {
      ParserRule _originalElement = AntlrGrammarGenUtil.<ParserRule>getOriginalElement(((ParserRule)rule));
      boolean _isDatatypeRule = GrammarUtil.isDatatypeRule(((AbstractRule) _originalElement));
      boolean _not = (!_isDatatypeRule);
      if (_not) {
        throw new IllegalStateException("crossrefEbnf is not supported for ParserRule that is not a datatype rule");
      }
    }
    _xblockexpression = this.crossrefEbnf(rule, it, ref, supportActions);
  }
  return _xblockexpression;
}
 
Example 8
Source File: KeywordCollector.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Boolean caseParserRule(final ParserRule object) {
  if (!GrammarUtil.isDatatypeRule(object)) {
    return false;
  }
  if (object.getType().getClassifier() == EcorePackage.Literals.ESTRING) {
    return doSwitch(object.getAlternatives());
  }
  return true;
}
 
Example 9
Source File: AntlrGrammarGenUtil.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.9
 */
public static String getArgumentList(final RuleCall ruleCall, boolean passCurrentIntoFragment, boolean isPredicate) {
	final List<NamedArgument> arguments = ruleCall.getArguments();
	AbstractRule abstractRule = ruleCall.getRule();
	boolean needsCurrent = passCurrentIntoFragment && GrammarUtil.isEObjectFragmentRule(abstractRule) && !GrammarUtil.isDatatypeRule((ParserRule) getOriginalElement(abstractRule));
	if (arguments.isEmpty()) {
		if (needsCurrent) {
			return isPredicate ? "[null]" : "[$current]";
		}
		return "";
	}
	ParserRule rule = (ParserRule) abstractRule;
	StringBuilder result = new StringBuilder();
	result.append("[");
	if (needsCurrent) {
		if (isPredicate) {
			result.append("null, ");
		} else {
			result.append("$current, ");
		}
	}
	Joiner.on(", ").appendTo(result, Iterables.transform(rule.getParameters(), new Function<Parameter, String>() {
		@Override
		public String apply(Parameter input) {
			for(NamedArgument argument: arguments) {
				if (argument.getParameter() == input) {
					return conditionToAntlr(argument.getValue(), true);
				}
			}
			throw new IllegalStateException("Cannot find argument for parameter: " + input.getName());
		}
	}));
	result.append("]");
	return result.toString();
}
 
Example 10
Source File: XtextValidator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkUnassignedRuleCallAllowed(final RuleCall call) {
	if (call.getRule() != null && !call.getRule().eIsProxy() && GrammarUtil.containingAssignment(call) == null) {
		AbstractRule container = GrammarUtil.containingRule(call);
		if (call.getRule() instanceof ParserRule) {
			if (container instanceof TerminalRule) {
				getMessageAcceptor().acceptError(
						"Cannot call parser rule from terminal rule.", 
						call, 
						XtextPackage.Literals.RULE_CALL__RULE,
						ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
						null);
			} else {
				ParserRule parserRule = (ParserRule) call.getRule();
				if (!GrammarUtil.isDatatypeRule(parserRule) && !parserRule.isFragment()) {
					checkCurrentMustBeUnassigned(call);
				}
			}
		}
		if (call.getRule() instanceof EnumRule) {
			if (container instanceof TerminalRule) {
				getMessageAcceptor().acceptError(
						"Cannot call enum rule from terminal rule.", 
						call, 
						XtextPackage.Literals.RULE_CALL__RULE,
						ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
						null);
			}
		}
	}
}
 
Example 11
Source File: DatatypeRuleUtil.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Boolean caseParserRule(ParserRule object) {
	if (visitedRules.isEmpty()) {
		visitedRules.add(object);
		return object.getAlternatives() != null && doSwitch(object.getAlternatives());
	}
	final TypeRef typeRef = object.getType();
	if (typeRef == null || typeRef.getClassifier() == null) {
		throw new IllegalStateException("checks are only allowed for linked grammars. Rule: " + object.getName());
	}
	if (!visitedRules.add(object))
		return true;
	Boolean result = GrammarUtil.isDatatypeRule(object);
	return result; 
}
 
Example 12
Source File: ValidEntryRuleInspector.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected boolean canInspect(ParserRule rule) {
	if (GrammarUtil.getGrammar(rule).getRules().get(0) != rule)
		return false;
	if (GrammarUtil.isDatatypeRule(rule) || rule.getAlternatives() == null)
		return false;
	return super.canInspect(rule);
}
 
Example 13
Source File: AbstractAntlrGrammarGenerator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected String compileEBNF(final AbstractRule it, final AntlrOptions options) {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("// Rule ");
  String _name = AntlrGrammarGenUtil.<AbstractRule>getOriginalElement(it).getName();
  _builder.append(_name);
  _builder.newLineIfNotEmpty();
  String _ruleName = this._grammarAccessExtensions.ruleName(it);
  _builder.append(_ruleName);
  String _compileInit = this.compileInit(it, options);
  _builder.append(_compileInit);
  _builder.append(":");
  _builder.newLineIfNotEmpty();
  {
    if (((it instanceof ParserRule) && GrammarUtil.isDatatypeRule(AntlrGrammarGenUtil.<AbstractRule>getOriginalElement(it)))) {
      _builder.append("\t");
      String _dataTypeEbnf = this.dataTypeEbnf(it.getAlternatives(), true);
      _builder.append(_dataTypeEbnf, "\t");
      _builder.newLineIfNotEmpty();
    } else {
      _builder.append("\t");
      String _ebnf = this.ebnf(it.getAlternatives(), options, true);
      _builder.append(_ebnf, "\t");
      _builder.newLineIfNotEmpty();
    }
  }
  _builder.append(";");
  _builder.newLine();
  String _compileFinally = this.compileFinally(it, options);
  _builder.append(_compileFinally);
  _builder.newLineIfNotEmpty();
  return _builder.toString();
}
 
Example 14
Source File: XtextValidator.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private boolean containsAnyParserRule(Grammar g, Set<Grammar> visited) {
	if (!visited.add(g))
		return false;
	for (AbstractRule rule : g.getRules()) {
		if (rule instanceof ParserRule && !GrammarUtil.isDatatypeRule((ParserRule) rule))
			return true;
	}
	for (Grammar used : g.getUsedGrammars()) {
		if (containsAnyParserRule(used, visited))
			return true;
	}
	return false;
}
 
Example 15
Source File: XtextLabelProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
StyledString text(ParserRule parserRule) {
	if (GrammarUtil.isDatatypeRule(parserRule)) {
		Styler xtextStyleAdapterStyler = stylerFactory.createXtextStyleAdapterStyler(semanticHighlightingConfiguration
				.dataTypeRule());
		return new StyledString(parserRule.getName(), xtextStyleAdapterStyler);
	}
	return convertToStyledString(parserRule.getName());
}
 
Example 16
Source File: CurrentTypeFinder.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Boolean caseRuleCall(RuleCall object) {
	EClassifier wasType = currentType;
	AbstractRule calledRule = object.getRule();
	if (currentType == null) {
		if (calledRule instanceof ParserRule && !GrammarUtil.isDatatypeRule((ParserRule) calledRule)) {
			ParserRule parserRule = (ParserRule) calledRule;
			if (parserRule.isFragment()) {
				if (context.getType() != null)
					currentType = context.getType().getClassifier();
				if (!parserRule.isWildcard()) {
					doSwitch(parserRule);
				}
			} else {
				TypeRef returnType = calledRule.getType();
				if (returnType != null) {
					currentType = returnType.getClassifier();
				}
			}
		}
	} else if (isFragmentButNotWildcard(calledRule)) {
		doSwitch(calledRule);
	}
	if (object == stopElement)
		return true;
	if (GrammarUtil.isOptionalCardinality(object))
		currentType = getCompatibleType(currentType, wasType, object);
	return false;
}
 
Example 17
Source File: SyntaxFilteredScopesTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test_05() {
	List<AbstractRule> rules = grammarAccess.getGrammar().getRules();
	for(AbstractRule rule: rules) {
		if (GrammarUtil.isDatatypeRule(rule)) {
			List<String> values1 = syntaxFilteredScopes.getEnumeratedValues((ParserRule) rule);
			List<String> values2 = getEnumeratedValues((ParserRule) rule);
			Collections.sort(values1);
			Collections.sort(values2);
			assertEquals(values1, values2);
		}
	}
}
 
Example 18
Source File: AntlrGrammarGenerator.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected String compileEntryRule(final ParserRule it, final Grammar grammar, final AntlrOptions options) {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("// Entry rule ");
  String _entryRuleName = this._grammarAccessExtensions.entryRuleName(AntlrGrammarGenUtil.<ParserRule>getOriginalElement(it));
  _builder.append(_entryRuleName);
  _builder.newLineIfNotEmpty();
  String _entryRuleName_1 = this._grammarAccessExtensions.entryRuleName(AntlrGrammarGenUtil.<ParserRule>getOriginalElement(it));
  _builder.append(_entryRuleName_1);
  _builder.append(" returns ");
  String _compileEntryReturns = this.compileEntryReturns(it, options);
  _builder.append(_compileEntryReturns);
  CharSequence _compileEntryInit = this.compileEntryInit(it, options);
  _builder.append(_compileEntryInit);
  _builder.append(":");
  _builder.newLineIfNotEmpty();
  _builder.append("\t");
  _builder.append("{ ");
  CharSequence _newCompositeNode = this.newCompositeNode(it);
  _builder.append(_newCompositeNode, "\t");
  _builder.append(" }");
  _builder.newLineIfNotEmpty();
  _builder.append("\t");
  _builder.append("iv_");
  String _ruleName = this._grammarAccessExtensions.ruleName(AntlrGrammarGenUtil.<ParserRule>getOriginalElement(it));
  _builder.append(_ruleName, "\t");
  _builder.append("=");
  String _ruleName_1 = this._grammarAccessExtensions.ruleName(it);
  _builder.append(_ruleName_1, "\t");
  String _defaultArgumentList = AntlrGrammarGenUtil.getDefaultArgumentList(it);
  _builder.append(_defaultArgumentList, "\t");
  _builder.newLineIfNotEmpty();
  _builder.append("\t");
  _builder.append("{ $current=$iv_");
  String _ruleName_2 = this._grammarAccessExtensions.ruleName(it);
  _builder.append(_ruleName_2, "\t");
  _builder.append(".current");
  {
    boolean _isDatatypeRule = GrammarUtil.isDatatypeRule(AntlrGrammarGenUtil.<ParserRule>getOriginalElement(it));
    if (_isDatatypeRule) {
      _builder.append(".getText()");
    }
  }
  _builder.append("; }");
  _builder.newLineIfNotEmpty();
  _builder.append("\t");
  _builder.append("EOF;");
  _builder.newLine();
  CharSequence _compileEntryFinally = this.compileEntryFinally(it, options);
  _builder.append(_compileEntryFinally);
  _builder.newLineIfNotEmpty();
  return _builder.toString();
}
 
Example 19
Source File: FollowElementCalculator.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Boolean caseParserRule(ParserRule object) {
	if (GrammarUtil.isDatatypeRule(object))
		return Boolean.FALSE;
	return doSwitch(object.getAlternatives());
}
 
Example 20
Source File: AbstractAntlrGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @since 2.8
 */
protected boolean hasProductionRules(Grammar grammar) {
	AbstractRule firstRule = grammar.getRules().get(0);
	return firstRule instanceof ParserRule && !GrammarUtil.isDatatypeRule((ParserRule) firstRule);
}