Java Code Examples for org.eclipse.xtext.AbstractRule#getType()

The following examples show how to use org.eclipse.xtext.AbstractRule#getType() . 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: XtextProposalProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Not a full featured solution for the computation of available structural features, but it is sufficient for some
 * interesting 85%.
 */
@Override
public void completeAssignment_Feature(EObject model, Assignment assignment, ContentAssistContext context,
		ICompletionProposalAcceptor acceptor) {
	AbstractRule rule = EcoreUtil2.getContainerOfType(model, AbstractRule.class);
	TypeRef typeRef = rule.getType();
	if (typeRef != null && typeRef.getClassifier() instanceof EClass) {
		Iterable<EStructuralFeature> features = ((EClass) typeRef.getClassifier()).getEAllStructuralFeatures();
		Function<IEObjectDescription, ICompletionProposal> factory = getProposalFactory(grammarAccess.getValidIDRule().getName(), context);
		Iterable<String> processedFeatures = completeStructuralFeatures(context, factory, acceptor, features);
		if(rule.getType().getMetamodel() instanceof GeneratedMetamodel) {
			if(notNull(rule.getName()).toLowerCase().startsWith("import")) {
				completeSpecialAttributeAssignment("importedNamespace", 2, processedFeatures, factory, context, acceptor); 
				completeSpecialAttributeAssignment("importURI", 1, processedFeatures, factory, context, acceptor); 
			} else {
				completeSpecialAttributeAssignment("name", 3, processedFeatures, factory, context, acceptor); 
			}
		}
	}
	super.completeAssignment_Feature(model, assignment, context, acceptor);
}
 
Example 2
Source File: Xtext2EcoreTransformer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private TypeRef getOrComputeReturnType(AbstractRule rule) {
	TypeRef result = rule.getType();
	if (result == null) {
		EClassifier classifier = getClassifierFor(rule);
		if (classifier == null) {
			if (rule.getName() == null)
				return null;
			result = getTypeRef(rule.getName());
		} else
			result = getTypeRef(classifier);
		if (result.getMetamodel() == null) {
			AbstractMetamodelDeclaration bestMatch = null;
			for (AbstractMetamodelDeclaration decl : grammar.getMetamodelDeclarations()) {
				if (decl instanceof GeneratedMetamodel && Strings.isEmpty(decl.getAlias())) {
					bestMatch = decl;
					break;
				}
			}
			if (result.getMetamodel() == null)
				result.setMetamodel(bestMatch);
		}
		rule.setType(result);
	}
	return result;
}
 
Example 3
Source File: SequenceFeeder.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void acceptRuleCall(RuleCall rc, Object value, String token, int index, INode node) {
	CrossReference crossRef = GrammarUtil.containingCrossReference(rc);
	if (crossRef != null) {
		if (rc.getRule() instanceof ParserRule)
			sequenceAcceptor.acceptAssignedCrossRefDatatype(rc, token, (EObject) value, index,
					getCompositeNode(node));
		else if (rc.getRule() instanceof TerminalRule)
			sequenceAcceptor.acceptAssignedCrossRefTerminal(rc, token, (EObject) value, index, getLeafNode(node));
		else if (rc.getRule() instanceof EnumRule)
			sequenceAcceptor.acceptAssignedCrossRefEnum(rc, token, (EObject) value, index, getCompositeNode(node));
	} else {
		if (rc.getRule() instanceof ParserRule) {
			AbstractRule rule = rc.getRule();
			if (rule.getType() != null && rule.getType().getClassifier() instanceof EClass)
				acceptEObjectRuleCall(rc, (EObject) value, getCompositeNode(node));
			else
				sequenceAcceptor.acceptAssignedDatatype(rc, token, value, index, getCompositeNode(node));
		} else if (rc.getRule() instanceof TerminalRule)
			sequenceAcceptor.acceptAssignedTerminal(rc, token, value, index, getLeafNode(node));
		else if (rc.getRule() instanceof EnumRule)
			sequenceAcceptor.acceptAssignedEnum(rc, token, value, index, getCompositeNode(node));
	}
}
 
Example 4
Source File: InheritanceTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testMetamodel() throws Exception {
	AbstractRule rule = GrammarUtil.findRuleForName(getGrammarAccess().getGrammar(), "OverridableParserRule2");
	assertNotNull("rule", rule);
	TypeRef ref = rule.getType();
	assertNotNull("ref", ref);
	final EClass clazz = (EClass) ref.getClassifier();
	assertNotNull("class", clazz);
	assertEquals("AType2", clazz.getName());
	assertEquals(2, clazz.getESuperTypes().size());
	Set<String> expectedNames = new HashSet<String>(Arrays.asList(new String[]{"AType", "RootRule"}));
	Iterator<String> iter = Iterables.transform(clazz.getESuperTypes(), new Function<EClass, String>(){
		@Override
		public String apply(EClass param) {
			return param.getName();
		}
	}).iterator();
	while(iter.hasNext()) {
		String name = iter.next();
		assertTrue("name = '" + name + "'", expectedNames.remove(name));
	}
	assertTrue(expectedNames.toString(), expectedNames.isEmpty());
}
 
Example 5
Source File: XtextHyperlinkHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void createHyperlinksByOffset(XtextResource resource, int offset, IHyperlinkAcceptor acceptor) {
	super.createHyperlinksByOffset(resource, offset, acceptor);
	EObject objectAtOffset = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
	if (objectAtOffset instanceof AbstractRule) {
		ITextRegion nameLocation = locationInFileProvider.getSignificantTextRegion(objectAtOffset, XtextPackage.Literals.ABSTRACT_RULE__NAME, 0);
		if (nameLocation != null && nameLocation.contains(offset)) {
			AbstractRule rule = (AbstractRule) objectAtOffset;
			createLinksToBase(nameLocation, rule, acceptor);
			if (rule.getType() != null && rule.getType().getClassifier() != null && NodeModelUtils.getNode(rule.getType()) == null) {
				createHyperlinksTo(resource, toRegion(nameLocation), rule.getType().getClassifier(), acceptor);
			}
		}
	}
}
 
Example 6
Source File: XtextOutlineTreeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected StyledString getReturnTypeText(AbstractRule rule) {
	StringBuilder typeName = new StringBuilder(NAME_TYPE_SEPARATOR);
	if (rule.getType() != null && rule.getType().getClassifier() != null && rule.getType().getMetamodel() != null) {
		String alias = rule.getType().getMetamodel().getAlias();
		if (alias != null) {
			typeName.append(alias);
			typeName.append(ALIAS_TYPE_SEPARATOR);
		}
		typeName.append(safeName(rule.getType().getClassifier().getName()));
	} else {
		typeName.append(safeName(rule.getName()));
	}
	StyledString styledType = new StyledString(typeName.toString(), StyledString.DECORATIONS_STYLER);
	return styledType;
}
 
Example 7
Source File: XtextRenameStrategyProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void renameReturnType(URI targetElementURI, String newName, ResourceSet resourceSet) {
	AbstractRule rule = (AbstractRule) resourceSet.getEObject(targetElementURI, false);
	TypeRef parserRuleType = rule.getType();
	if (rule.getName().equals(parserRuleType.getClassifier().getName())
			&& parserRuleType.getMetamodel() instanceof GeneratedMetamodel) {
		parserRuleType.getClassifier().setName(newName);
	}
}
 
Example 8
Source File: Xtext2EcoreTransformer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
EClassifier getClassifierFor(AbstractRule rule) {
	if (rule.getType() != null && rule.getType().getClassifier() != null)
		return rule.getType().getClassifier();
	if (rule instanceof TerminalRule || rule instanceof ParserRule && DatatypeRuleUtil.isDatatypeRule((ParserRule) rule)) {
		return GrammarUtil.findEString(grammar);
	}
	return null;
}
 
Example 9
Source File: Xtext2EcoreTransformer.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private EClassifierInfo findEClassifierInfo(AbstractRule rule) {
	final TypeRef typeRef = getOrComputeReturnType(rule);
	if (typeRef == null)
		throw new NullPointerException();
	if (rule.getType() != typeRef)
		throw new IllegalStateException();
	return eClassifierInfos.getInfo(typeRef);
}
 
Example 10
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 11
Source File: Xtext2EcoreTransformerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTypesOfImplicitSuperGrammar() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("grammar test with org.eclipse.xtext.common.Terminals");
  _builder.newLine();
  _builder.append("generate test \'http://test\'");
  _builder.newLine();
  _builder.append("MyRule: myFeature=INT;");
  _builder.newLine();
  final String xtextGrammar = _builder.toString();
  EObject _model = this.getModel(xtextGrammar);
  final Grammar grammar = ((Grammar) _model);
  final Xtext2EcoreTransformer transformer = new Xtext2EcoreTransformer(grammar);
  transformer.removeGeneratedPackages();
  transformer.transform();
  final AbstractRule rule = IterableExtensions.<AbstractRule>head(grammar.getRules());
  TypeRef type = rule.getType();
  Assert.assertNotNull(type);
  Assert.assertNotNull(transformer.getEClassifierInfos().getInfo(type));
  AbstractMetamodelDeclaration _get = GrammarUtil.allMetamodelDeclarations(grammar).get(1);
  final ReferencedMetamodel referenced = ((ReferencedMetamodel) _get);
  Assert.assertNotNull(referenced);
  Assert.assertEquals("ecore", referenced.getAlias());
  Assert.assertNull(transformer.getEClassifierInfos().getInfo(referenced, "EString"));
  Assert.assertNull(transformer.getEClassifierInfos().getInfo(referenced, "EInt"));
  EClassifierInfos parentInfos = IterableExtensions.<EClassifierInfos>head(transformer.getEClassifierInfos().getParents());
  Assert.assertNotNull(parentInfos.getInfo(referenced, "EString"));
  Assert.assertNotNull(parentInfos.getInfo(referenced, "EInt"));
}
 
Example 12
Source File: Xtext2EcoreTransformer.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
private boolean deriveTypeHierarchy() {
	boolean result = true;
	for (AbstractRule rule : grammar.getRules()) {
		try {
			EClassifierInfo generatedEClass = findOrCreateEClassifierInfo(rule);
			if (generatedEClass != null || !isWildcardFragment(rule)) {
				if (rule instanceof ParserRule) {
					ParserRule parserRule = (ParserRule) rule;
					if (parserRule.getAlternatives() != null) {
						if (!GrammarUtil.isDatatypeRule(parserRule)) {
							deriveTypesAndHierarchy(parserRule, generatedEClass, parserRule.getAlternatives());
						} else {
							checkSupertypeOfOverriddenDatatypeRule(rule);
						}
					}
				} else if (rule instanceof TerminalRule) {
					if (rule.getType() != null) {
						if (!(rule.getType().getClassifier() instanceof EDataType))
							throw new TransformationException(TransformationErrorCode.NoSuchTypeAvailable,
									"Return type of a terminal rule must be an EDataType.", rule.getType());
						checkSupertypeOfOverriddenDatatypeRule(rule);
					}
				} else if (rule instanceof EnumRule) {
					if (rule.getType() != null) {
						if (!(rule.getType().getClassifier() instanceof EEnum))
							throw new TransformationException(TransformationErrorCode.NoSuchTypeAvailable,
									"Return type of an enum rule must be an EEnum.", rule.getType());
						checkSupertypeOfOverriddenDatatypeRule(rule);
					}
				} else {
					throw new IllegalStateException("Unknown rule type: " + rule.eClass().getName());
				}
			}
			if (isWildcardFragment(rule)) {
				for (Grammar usedGrammar: grammar.getUsedGrammars()) {
					deriveTypeHierarchyFromOverridden((ParserRule) rule, usedGrammar);
				}
			}
		}
		catch (TransformationException e) {
			reportError(e);
			result = false;
		}
	}
	return result;
}
 
Example 13
Source File: Xtext2EcoreTransformer.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
private boolean deriveTypeHierarchyFromOverridden(ParserRule rule, Grammar grammar) throws TransformationException {
	AbstractRule parentRule = GrammarUtil.findRuleForName(grammar, rule.getName());
	if (parentRule != null) {
		if (parentRule != rule && parentRule instanceof ParserRule) {
			ParserRule casted = (ParserRule) parentRule;
			if (casted.isFragment() != rule.isFragment()) {
				if (rule.isFragment()) {
					throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride,
							"A fragment rule cannot override a production rule.", rule);
				} else {
					throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride,
							"Only fragment rule can override other fragment rules.", rule);
				}
			}
			if (casted.isWildcard() != rule.isWildcard()) {
				if (rule.isWildcard()) {
					throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride,
							"A wildcard fragment rule cannot override a typed fragment rule.", rule);
				} else {
					throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride,
							"Only wildcard fragment rules can override other wildcard fragments.", rule);
				}
			}
			if (rule.isFragment() && !rule.isWildcard() && parentRule.getType() != null) {
				if (rule.getType().getClassifier() != parentRule.getType().getClassifier()) {
					throw new TransformationException(TransformationErrorCode.InvalidFragmentOverride,
							"Overriding fragment rules cannot redeclare their type.", rule.getType());
				}
			}
			checkParameterLists(rule, casted);
		}
		if (parentRule.getType() != null && parentRule != rule) {			
			if (parentRule.getType().getClassifier() instanceof EDataType)
				throw new TransformationException(TransformationErrorCode.InvalidSupertype,
						"Cannot inherit from datatype rule and return another type.", rule.getType());
			EClassifierInfo parentTypeInfo = eClassifierInfos.getInfoOrNull(parentRule.getType());
			if (parentTypeInfo == null)
				throw new TransformationException(TransformationErrorCode.InvalidSupertype,
						"Cannot determine return type of overridden rule.", rule.getType());
			addSuperType(rule, rule.getType(), parentTypeInfo);
			return true;
		}
	}
	return false;
}
 
Example 14
Source File: ElementTypeCalculator.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public EClassifier caseAbstractRule(AbstractRule object) {
	if (object.getType() != null)
		return doSwitch(object.getType());
	return null;
}