@Override public String[] getExportedPackagesRt(Grammar grammar) { List<GeneratedMetamodel> typeSelect = org.eclipse.xtext.EcoreUtil2.typeSelect( grammar.getMetamodelDeclarations(), GeneratedMetamodel.class); Set<String> exportedPackages = new LinkedHashSet<String>(); if (modelPluginID == null) { for (GeneratedMetamodel generatedMetamodel : typeSelect) { final String modelPackage = Strings.skipLastToken( getGeneratedEPackageName(grammar, generatedMetamodel.getEPackage()), "."); exportedPackages.add(modelPackage); exportedPackages.add(modelPackage + ".impl"); exportedPackages.add(modelPackage + ".util"); } } return exportedPackages.toArray(new String[exportedPackages.size()]); }
@Override public void process(GeneratedMetamodel metamodel) { if (!metamodel.getName().equals("reactionsLanguage")) return; final EPackage ePackage = metamodel.getEPackage(); final EClass reactionsSegmentEClass = getEClass(ePackage, "ReactionsSegment"); final EClass reactionEClass = getEClass(ePackage, "Reaction"); final EClass effectEClass = getEClass(ePackage, "Routine"); // Add an opposite reference for the metamodel pair to the reaction final EReference reactionsSegmentReactionsReference = (EReference)reactionsSegmentEClass.getEStructuralFeature("reactions"); addReactionsSegmentEReference(reactionEClass, reactionsSegmentReactionsReference); final EReference reactionsSegmentEffectsReference = (EReference)reactionsSegmentEClass.getEStructuralFeature("routines"); addReactionsSegmentEReference(effectEClass, reactionsSegmentEffectsReference); }
@Override public void process(GeneratedMetamodel metamodel) { Resource xtendFile = loadXtendFile(metamodel); if (xtendFile != null) { ExecutionContext ctx = getExecutionContext(metamodel); ctx = ctx.cloneWithResource(xtendFile); ResourceLoader currentThreadResourceLoader = null; try { currentThreadResourceLoader = getCurrentThreadResourceLoader(); setCurrentThreadResourceLoader(getResourceLoader(metamodel)); final Object[] params = new Object[] { metamodel }; Extension extension = ctx.getExtension("process", params); if (extension != null) { extension.evaluate(params, ctx); } } catch (EvaluationException e) { logger.error("Error encountered processing metamodel " + metamodel.getName() + " with " + xtendFile.getFullyQualifiedName(), e); } finally { setCurrentThreadResourceLoader(currentThreadResourceLoader); } } }
public List<EPackage> getGeneratedPackages() { final List<EPackage> result = new ArrayList<EPackage>(); final ResourceSet resourceSet = grammar.eResource().getResourceSet(); if (resourceSet == null) throw new NullPointerException("resourceSet may not be null"); Iterables.addAll(result, Iterables.filter(Iterables.transform( Iterables.filter(grammar.getMetamodelDeclarations(), GeneratedMetamodel.class), new Function<AbstractMetamodelDeclaration, EPackage>() { @Override public EPackage apply(AbstractMetamodelDeclaration param) { EPackage pack = (EPackage) param.eGet(XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, false); if (pack != null && !pack.eIsProxy()) { return pack; } return null; } }), Predicates.notNull())); return getPackagesSortedByName(result); }
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; }
void discardGeneratedPackages(EObject root) { if (root instanceof Grammar) { // unload generated metamodels as they will be recreated during linking for (AbstractMetamodelDeclaration metamodelDeclaration : ((Grammar) root).getMetamodelDeclarations()) { if (metamodelDeclaration instanceof GeneratedMetamodel) { EPackage ePackage = (EPackage) metamodelDeclaration.eGet(XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, false); if (ePackage != null && !ePackage.eIsProxy()) { Resource resource = ePackage.eResource(); if (resource != null && resource.getResourceSet() != null) { if (unloader != null) { for (EObject content : resource.getContents()) { unloader.unloadRoot(content); } } resource.getResourceSet().getResources().remove(resource); } } } } } }
private void doPropagateValidationResult(Diagnostic diagnostic, GeneratedMetamodel metamodel, ValidationMessageAcceptor acceptor) { boolean foundEObject = false; Object firstData = null; for(Object data: diagnostic.getData()) { if (firstData == null) { firstData = diagnostic.getData().get(0); } if (data instanceof EObject) { if (createMessageForSource(diagnostic, (EObject) data, acceptor)) { foundEObject = true; } if (data instanceof EStructuralFeature && ((EStructuralFeature) data).getEContainingClass() != firstData) { EClass containingClass = ((EStructuralFeature) data).getEContainingClass(); createMessageForSource(diagnostic, containingClass, acceptor); } } } if (!foundEObject) { doCreateMessage( diagnostic, metamodel, XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, acceptor); } }
@Check public void checkReferencedMetamodel(ReferencedMetamodel metamodel) throws ValueConverterException { if (metamodel.getEPackage() == null) return; String nsURI = metamodel.getEPackage().getNsURI(); List<GeneratedMetamodel> allGeneratedMetamodels = getInheritedGeneratedMetamodels(metamodel); String text = getUsedUri(metamodel); for (GeneratedMetamodel generatedMetamodel : allGeneratedMetamodels) { EPackage generatedPackage = generatedMetamodel.getEPackage(); if (generatedPackage != null && nsURI.equals((generatedPackage.getNsURI()))) { if (!text.equals(nsURI)) { addIssue("Metamodels that have been generated by a super grammar must be referenced by nsURI: " + nsURI, metamodel, XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, INVALID_PACKAGE_REFERENCE_INHERITED, nsURI); return; } return; } } checkExternalPackage(metamodel, text); }
@Check public void checkGeneratedEnumIsValid(EnumLiteralDeclaration decl) { EnumRule rule = GrammarUtil.containingEnumRule(decl); if (!(rule.getType().getMetamodel() instanceof GeneratedMetamodel)) return; if (!(rule.getType().getClassifier() instanceof EEnum)) return; EEnum eEnum = (EEnum) rule.getType().getClassifier(); List<EnumLiteralDeclaration> declarations = EcoreUtil2.getAllContentsOfType(rule, EnumLiteralDeclaration.class); if (declarations.size() == eEnum.getELiterals().size()) return; for (EnumLiteralDeclaration otherDecl : declarations) { if (decl == otherDecl) { return; } if (otherDecl.getEnumLiteral() == decl.getEnumLiteral()) { if (!decl.getEnumLiteral().getLiteral().equals(decl.getLiteral().getValue())) addIssue("Enum literal '" + decl.getEnumLiteral().getName() + "' has already been defined with literal '" + decl.getEnumLiteral().getLiteral() + "'.", decl, XtextPackage.Literals.ENUM_LITERAL_DECLARATION__ENUM_LITERAL, DUPLICATE_ENUM_LITERAL); return; } } }
private List<EObject> createPackage(GeneratedMetamodel generatedMetamodel, ILeafNode text) { final String nsURI = getMetamodelNsURI(text); final URI uri = URI.createURI(nsURI); if (uri == null || isReferencedByUsedGrammar(generatedMetamodel, nsURI)) return Collections.emptyList(); EPackage pack = ((GeneratedMetamodelImpl)generatedMetamodel).basicGetEPackage(); if (pack != null && !pack.eIsProxy()) return singletonList((EObject)pack); final EPackage generatedEPackage = EcoreFactory.eINSTANCE.createEPackage(); generatedEPackage.setName(generatedMetamodel.getName()); generatedEPackage.setNsPrefix(generatedMetamodel.getName()); generatedEPackage.setNsURI(nsURI); final Resource generatedPackageResource = new EcoreResourceFactoryImpl().createResource(uri); XtextResourceSet resourceSet = (XtextResourceSet) generatedMetamodel.eResource().getResourceSet(); if (!resourceSet.getURIResourceMap().containsKey(generatedPackageResource.getURI())) { generatedMetamodel.eResource().getResourceSet().getResources().add(generatedPackageResource); } else { generatedPackageResource.setURI(URI.createURI(nsURI+"_"+generatedMetamodel.hashCode())); generatedMetamodel.eResource().getResourceSet().getResources().add(generatedPackageResource); } generatedPackageResource.getContents().add(generatedEPackage); return Collections.<EObject>singletonList(generatedEPackage); }
@Test public void testCycleInTypeHierarchy() throws Exception { String grammarAsText = "grammar test with org.eclipse.xtext.common.Terminals" + " generate test 'http://test'"; grammarAsText += " RuleA: RuleB;"; grammarAsText += " RuleB: RuleC;"; grammarAsText += " RuleC: RuleA;"; grammarAsText += " RuleD: RuleA;"; Grammar grammar = (Grammar) getModel(grammarAsText); AbstractMetamodelDeclaration metamodelDeclaration = grammar.getMetamodelDeclarations().get(0); XtextValidator validator = get(XtextValidator.class); ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(grammar.getRules().get(0).getType(), true, false); messageAcceptor.expectedContext( grammar.getRules().get(1).getType(), grammar.getRules().get(2).getType() ); validator.setMessageAcceptor(messageAcceptor); validator.checkGeneratedPackage((GeneratedMetamodel) metamodelDeclaration, Diagnostician.INSTANCE, Collections.EMPTY_MAP); messageAcceptor.validate(); }
@Test public void testNameClash_01() throws Exception { String grammarAsText = "grammar test with org.eclipse.xtext.common.Terminals\n" + "generate test 'http://test'\n" + "PRINTF: vars=PRINTF_Vars;\n" + "PRINTF_Vars: arg1=ID;"; Grammar grammar = (Grammar) getModel(grammarAsText); AbstractMetamodelDeclaration metamodelDeclaration = grammar.getMetamodelDeclarations().get(0); XtextValidator validator = get(XtextValidator.class); ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(null, true, false); messageAcceptor.expectedContext( grammar.getRules().get(0).getAlternatives(), grammar.getRules().get(1).getType() ); validator.setMessageAcceptor(messageAcceptor); validator.checkGeneratedPackageForNameClashes((GeneratedMetamodel) metamodelDeclaration); messageAcceptor.validate(); }
@Test public void testNameClash_02() throws Exception { String grammarAsText = "grammar test with org.eclipse.xtext.common.Terminals\n" + "generate test 'http://test'\n" + "Class returns Class: {Class_} name=ID;\n"; Grammar grammar = (Grammar) getModel(grammarAsText); AbstractMetamodelDeclaration metamodelDeclaration = grammar.getMetamodelDeclarations().get(0); XtextValidator validator = get(XtextValidator.class); ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(null, true, false); CompoundElement element = (CompoundElement) grammar.getRules().get(0).getAlternatives(); messageAcceptor.expectedContext( grammar.getRules().get(0).getType(), ((Action) element.getElements().get(0)).getType() ); validator.setMessageAcceptor(messageAcceptor); validator.checkGeneratedPackage((GeneratedMetamodel) metamodelDeclaration, Diagnostician.INSTANCE, Collections.EMPTY_MAP); messageAcceptor.validate(); }
@Test public void testNameClash_03() throws Exception { String grammarAsText = "grammar test with org.eclipse.xtext.common.Terminals\n" + "generate test 'http://test'\n" + "Foo: myVars=ID my_vars=ID;\n"; Grammar grammar = (Grammar) getModel(grammarAsText); AbstractMetamodelDeclaration metamodelDeclaration = grammar.getMetamodelDeclarations().get(0); XtextValidator validator = get(XtextValidator.class); ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(null, true, false); CompoundElement element = (CompoundElement) grammar.getRules().get(0).getAlternatives(); messageAcceptor.expectedContext( grammar.getRules().get(0).getType(), element.getElements().get(0), element.getElements().get(1) ); validator.setMessageAcceptor(messageAcceptor); validator.checkGeneratedPackage((GeneratedMetamodel) metamodelDeclaration, Diagnostician.INSTANCE, Collections.EMPTY_MAP); messageAcceptor.validate(); }
@Override protected List<Object> getParameters(Grammar grammar) { List<String> packageQNames = new ArrayList<String>(); List<GeneratedMetamodel> list = EcoreUtil2.typeSelect(grammar.getMetamodelDeclarations(), GeneratedMetamodel.class); for (GeneratedMetamodel generatedMetamodel : list) { packageQNames.add(getGeneratedEPackageName(grammar, getNaming(), generatedMetamodel.getEPackage())); } List<Object> parameters = Lists.newArrayList((Object) packageQNames); parameters.add(this.composedChecks); parameters.add(getValidatorSuperClassName(grammar)); return parameters; }
@Override protected void checkConfigurationInternal(Issues issues) { naming.setProjectNameRt(getProjectNameRt()); naming.setProjectNameIde(getProjectNameIde()); naming.setIdeBasePackage(!isIde() && isUi() ? getProjectNameUi() : getProjectNameIde()); naming.setProjectNameUi(getProjectNameUi()); naming.setUiBasePackage(getProjectNameUi()); naming.setActivatorName(getActivator()); naming.setPathTestProject(getPathTestProject()); naming.setFileHeader(getFileHeader()); naming.setClassAnnotations(getClassAnnotationsAsString()); naming.setAnnotationImports(getAnnotationImportsAsString()); naming.setHasUI(isUi()); naming.setHasIde(isIde()); Map<String, Grammar> uris = new HashMap<String, Grammar>(); for (LanguageConfig config : languageConfigs) { config.registerNaming(naming); config.checkConfiguration(issues); Grammar grammar = config.getGrammar(); List<GeneratedMetamodel> select = EcoreUtil2.typeSelect(grammar.getMetamodelDeclarations(), GeneratedMetamodel.class); for (GeneratedMetamodel generatedMetamodel : select) { String nsURI = generatedMetamodel.getEPackage().getNsURI(); if (uris.containsKey(nsURI)) { issues.addError("Duplicate generated grammar with nsURI '" + nsURI + "' in " + uris.get(nsURI).getName() + " and " + grammar.getName()); } else { uris.put(nsURI, grammar); } } } if (getProjectNameRt() == null) issues.addError("The property 'projectNameRt' is mandatory"); if (isUiMergedIntoRt() && getPathIdeProject() != null && ! isIdeMergedIntoRt()) { issues.addError("Cannot have a dedicated ide project when ui project is merged into runtime project"); } }
protected Collection<EPackage> getRegistryPackagesToValidate() { Collection<EPackage> _xblockexpression = null; { final Collection<EPackage> packages = GrammarUtil.allEPackagesToValidate(this.grammar); final Function1<GeneratedMetamodel, EPackage> _function = (GeneratedMetamodel it) -> { return it.getEPackage(); }; packages.removeAll( IterableExtensions.<EPackage>toList(IterableExtensions.<GeneratedMetamodel, EPackage>map(Iterables.<GeneratedMetamodel>filter(GrammarUtil.allMetamodelDeclarations(this.grammar), GeneratedMetamodel.class), _function))); _xblockexpression = packages; } return _xblockexpression; }
@Override public void process(final GeneratedMetamodel metamodel) { boolean _equals = this.testMetamodel.equals(metamodel); if (_equals) { this.called++; } }
/** * Expects an Xtend file named <code>MyDsl</code>PostProcessor.ext with an extension with signature * process(xtext::GeneratedMetamodel) in the same folder as the grammar file. * * @param metamodel * the metamodel to augment * @return the xtendFile to execute */ protected Resource loadXtendFile(GeneratedMetamodel metamodel) { if (xtendFile == null) { final String extension = getExtensionName(metamodel); try { URI uri = getXtendFileLocation(metamodel); if (uri != null) { URIConverter uriConverter = metamodel.eResource().getResourceSet().getURIConverter(); if (uriConverter.exists(uri, null)) { InputStream in = uriConverter.createInputStream(uri); try { XtendResourceParser parser = new XtendResourceParser(); xtendFile = parser.parse(new InputStreamReader(in), extension + '.' + XtendFile.FILE_EXTENSION); fireXtendFileLoaded(); } finally { if (in != null) in.close(); } } } } catch (ClasspathUriResolutionException ignored) { // no xtend file found } catch (Exception e) { logger.error("Could not parse " + extension, e); } } return xtendFile; }
protected URI getXtendFileLocation(GeneratedMetamodel metamodel) { URI uri = metamodel.eResource().getURI(); // check if uri can be used for resolve if (!uri.isHierarchical() || uri.isRelative()) return null; uri = URI.createURI(Strings.lastToken(getExtensionName(metamodel), "::")).appendFileExtension( XtendFile.FILE_EXTENSION).resolve(uri); return uri; }
private Set<String> getGeneratedEPackageURIs() { List<GeneratedMetamodel> list = EcoreUtil2.typeSelect(grammar.getMetamodelDeclarations(), GeneratedMetamodel.class); return Sets.newLinkedHashSet(Iterables.transform(list, new Function<GeneratedMetamodel, String>() { @Override public String apply(GeneratedMetamodel from) { return from.getEPackage()!=null?from.getEPackage().getNsURI() : null; } })); }
private void addGeneratedEPackage(GeneratedMetamodel generatedMetamodel) throws TransformationException { // we do not allow the same alias twice for generated metamodels String alias = Strings.emptyIfNull(generatedMetamodel.getAlias()); if (generatedEPackages.containsKey(alias)) throw new TransformationException(TransformationErrorCode.AliasForMetamodelAlreadyExists, "alias '" + alias + "' already exists", generatedMetamodel); if (generatedMetamodel.getEPackage() == null) throw new TransformationException(TransformationErrorCode.UnknownMetaModelAlias, "Cannot create EPackage without NsURI.", generatedMetamodel); // instantiate EPackages for generated metamodel EPackage generatedEPackage = generatedMetamodel.getEPackage(); generatedEPackages.put(alias, generatedEPackage); collectClassInfosOf(generatedEPackage, generatedMetamodel); }
private void postProcessGeneratedPackages() { if (postProcessor != null) { final Iterable<GeneratedMetamodel> generatedMetamodels = Iterables.filter(grammar .getMetamodelDeclarations(), GeneratedMetamodel.class); for (GeneratedMetamodel metamodel : generatedMetamodels) { postProcessor.process(metamodel); } } }
@Check public void checkGeneratedMetamodel(GeneratedMetamodel metamodel) { if (metamodel.getName() != null && metamodel.getName().length() != 0) if (Character.isUpperCase(metamodel.getName().charAt(0))) addIssue("Metamodel names should start with a lower case letter.", metamodel, XtextPackage.Literals.GENERATED_METAMODEL__NAME, INVALID_METAMODEL_NAME, metamodel.getName()); }
@Check public void checkGeneratedPackage(GeneratedMetamodel metamodel) { Map<Object, Object> context = getContext(); if (context != null) { Diagnostician diagnostician = (Diagnostician) context.get(EValidator.class); if (diagnostician != null) checkGeneratedPackage(metamodel, diagnostician, context); } }
@Check public void checkGeneratedPackageForNameClashes(GeneratedMetamodel metamodel) { EPackage pack = metamodel.getEPackage(); Multimap<String, ENamedElement> constantNameToElement = HashMultimap.create(); Multimap<String, ENamedElement> accessorNameToElement = HashMultimap.create(); if (pack != null) { for(EClassifier classifier: pack.getEClassifiers()) { String accessorName = classifier.getName(); if ("Class".equals(accessorName) || "Name".equals(accessorName)) accessorName += "_"; accessorNameToElement.put("get" + accessorName, classifier); String classifierConstantName = CodeGenUtil2.format(classifier.getName(), '_', null, true, true).toUpperCase(); constantNameToElement.put(classifierConstantName, classifier); if (classifier instanceof EClass) { for(EStructuralFeature feature: ((EClass) classifier).getEAllStructuralFeatures()) { String featureConstantPart = CodeGenUtil2.format(feature.getName(), '_', null, false, false).toUpperCase(); String featureConstantName = classifierConstantName + "__" + featureConstantPart; constantNameToElement.put(featureConstantName, feature); String featureAccessorName = "get" + classifier.getName() + "_" + Strings.toFirstUpper(feature.getName()); accessorNameToElement.put(featureAccessorName, feature); } } } } createMessageForNameClashes(constantNameToElement); createMessageForNameClashes(accessorNameToElement); }
@Check public void checkGeneratedPackageNotEmpty(GeneratedMetamodel metamodel) { EPackage pack = metamodel.getEPackage(); if (pack != null && pack.getEClassifiers().isEmpty()) { getMessageAcceptor().acceptError( "Generated package '" + metamodel.getName() + "' may not be empty.", metamodel, XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, EMPTY_GENERATED_PACKAGE); } }
private void propageValidationResult(Diagnostic diagnostic, GeneratedMetamodel metamodel, ValidationMessageAcceptor acceptor) { if (diagnostic.getSeverity() != Diagnostic.OK) { if (diagnostic.getCode() != 0) { List<?> data = diagnostic.getData(); if (!data.isEmpty() && data.get(0) instanceof EObject) { doPropagateValidationResult(diagnostic, metamodel, acceptor); } } for(Diagnostic child: diagnostic.getChildren()) propageValidationResult(child, metamodel, acceptor); } }
protected List<GeneratedMetamodel> getInheritedGeneratedMetamodels(ReferencedMetamodel metamodel) { List<GeneratedMetamodel> allGeneratedMetamodels = new ArrayList<GeneratedMetamodel>(); Grammar grammar = GrammarUtil.getGrammar(metamodel); Set<Grammar> visited = Sets.newHashSet(); for (Grammar usedGrammar : grammar.getUsedGrammars()) Iterables.addAll(allGeneratedMetamodels, getAllGeneratedMetamodels(usedGrammar, visited)); if (allGeneratedMetamodels.isEmpty()) return Collections.emptyList(); return allGeneratedMetamodels; }
private Iterable<GeneratedMetamodel> getAllGeneratedMetamodels(Grammar grammar, Set<Grammar> visited) { Iterable<GeneratedMetamodel> result = Iterables.filter(grammar.getMetamodelDeclarations(), GeneratedMetamodel.class); for (Grammar gr : grammar.getUsedGrammars()) { if (visited.add(gr)) result = Iterables.concat(result, getAllGeneratedMetamodels(gr, visited)); } return result; }
@Override protected EStructuralFeature getIdentifierFeature(EObject obj) { if (obj instanceof AbstractMetamodelDeclaration) { AbstractMetamodelDeclaration decl = (AbstractMetamodelDeclaration) obj; if (decl.getAlias() != null) return XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__ALIAS; if (decl instanceof GeneratedMetamodel && ((GeneratedMetamodel) decl).getName() != null) return XtextPackage.Literals.GENERATED_METAMODEL__NAME; return XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE; } return super.getIdentifierFeature(obj); }
@Override public List<EObject> getLinkedObjects(EObject context, EReference ref, INode node) throws IllegalNodeException { if (ref == XtextPackage.eINSTANCE.getGrammar_UsedGrammars()) return getUsedGrammar((Grammar) context, node); if (ref == XtextPackage.eINSTANCE.getTypeRef_Metamodel()) return getLinkedMetaModel((TypeRef)context, ref, (ILeafNode) node); if (ref == XtextPackage.eINSTANCE.getAbstractMetamodelDeclaration_EPackage() && context instanceof GeneratedMetamodel) return createPackage((GeneratedMetamodel) context, (ILeafNode) node); if (ref == XtextPackage.eINSTANCE.getAbstractMetamodelDeclaration_EPackage() && context instanceof ReferencedMetamodel) return getPackage((ReferencedMetamodel)context, (ILeafNode) node); return super.getLinkedObjects(context, ref, node); }
private boolean isReferencedByUsedGrammar(GeneratedMetamodel generatedMetamodel, String nsURI) { final Grammar grammar = GrammarUtil.getGrammar(generatedMetamodel); if (grammar != null) { final Set<Grammar> visitedGrammars = Sets.newHashSet(grammar); for (Grammar usedGrammar: grammar.getUsedGrammars()) { if (isReferencedByUsedGrammar(usedGrammar, nsURI, visitedGrammars)) return true; } } return false; }
protected Collection<EPackage> getRegistryPackagesToValidate() { final Collection<EPackage> packages = GrammarUtil.allEPackagesToValidate(this.getGrammar()); final Function1<GeneratedMetamodel, EPackage> _function = (GeneratedMetamodel it) -> { return it.getEPackage(); }; packages.removeAll(IterableExtensions.<EPackage>toList(IterableExtensions.<GeneratedMetamodel, EPackage>map(Iterables.<GeneratedMetamodel>filter(GrammarUtil.allMetamodelDeclarations(this.getGrammar()), GeneratedMetamodel.class), _function))); return packages; }
@Override protected void checkConfigurationInternal(final Issues issues) { this.initialize(); final MweIssues generatorIssues = new MweIssues(this, issues); this.configuration.checkConfiguration(generatorIssues); final HashMap<String, Grammar> uris = new HashMap<String, Grammar>(); for (final XtextGeneratorLanguage language : this.languageConfigs) { { language.checkConfiguration(generatorIssues); Iterable<GeneratedMetamodel> _filter = Iterables.<GeneratedMetamodel>filter(language.getGrammar().getMetamodelDeclarations(), GeneratedMetamodel.class); for (final GeneratedMetamodel generatedMetamodel : _filter) { { final String nsURI = generatedMetamodel.getEPackage().getNsURI(); boolean _containsKey = uris.containsKey(nsURI); if (_containsKey) { String _name = uris.get(nsURI).getName(); String _plus = ((("Duplicate generated grammar with nsURI \'" + nsURI) + "\' in ") + _name); String _plus_1 = (_plus + " and "); String _name_1 = language.getGrammar().getName(); String _plus_2 = (_plus_1 + _name_1); generatorIssues.addError(_plus_2); } else { uris.put(nsURI, language.getGrammar()); } } } } } }
@Test public void testDuplicateFeatures_01() throws Exception { String grammarAsText = "grammar test with org.eclipse.xtext.common.Terminals\n" + "generate test 'http://test'\n" + "Model: Parent1 | Parent2 | NoParent;\n" + "NoParent: foo=ID;" + "Parent1: Sub1 | Sub2;\n" + "Parent2: Sub2 | Sub3;\n" + "Sub1: x=ID;\n" + "Sub2: x=ID;\n" + "Sub3: x=ID;\n"; Grammar grammar = (Grammar) getModel(grammarAsText); AbstractMetamodelDeclaration metamodelDeclaration = grammar.getMetamodelDeclarations().get(0); XtextValidator validator = get(XtextValidator.class); ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(null, true, false); messageAcceptor.expectedContext( grammar.getRules().get(2).getType(), grammar.getRules().get(3).getType(), grammar.getRules().get(5).getType(), grammar.getRules().get(4).getAlternatives(), grammar.getRules().get(5).getAlternatives(), grammar.getRules().get(6).getAlternatives() ); validator.setMessageAcceptor(messageAcceptor); validator.checkGeneratedPackage((GeneratedMetamodel) metamodelDeclaration, Diagnostician.INSTANCE, Collections.EMPTY_MAP); messageAcceptor.validate(); }
@Test public void testDuplicateFeatures_02() throws Exception { String grammarAsText = "grammar test with org.eclipse.xtext.common.Terminals\n" + "generate test 'http://test'\n" + "A : (b+=B)*;\n" + "B : C | D;\n" + "C : 'c' name=ID ('e' e+=E)+;\n" + "E : name=ID;\n" + "F : C | E;\n" + "D : 'd' name=ID 'ref' ref=[F];"; Grammar grammar = (Grammar) getModel(grammarAsText); AbstractMetamodelDeclaration metamodelDeclaration = grammar.getMetamodelDeclarations().get(0); XtextValidator validator = get(XtextValidator.class); ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(null, true, false); messageAcceptor.expectedContext( grammar.getRules().get(1).getType(), grammar.getRules().get(2).getType(), grammar.getRules().get(4).getType(), ((CompoundElement) grammar.getRules().get(2).getAlternatives()).getElements().get(1), grammar.getRules().get(3).getAlternatives(), ((CompoundElement) grammar.getRules().get(5).getAlternatives()).getElements().get(1) ); validator.setMessageAcceptor(messageAcceptor); validator.checkGeneratedPackage((GeneratedMetamodel) metamodelDeclaration, Diagnostician.INSTANCE, Collections.EMPTY_MAP); messageAcceptor.validate(); }
@Test public void testGeneratedPackageNotEmpty() throws Exception { String grammarAsText = "grammar test with org.eclipse.xtext.common.Terminals\n" + "generate test 'http://test'\n" + "Foo: 'a';\n"; Grammar grammar = (Grammar) getModel(grammarAsText); AbstractMetamodelDeclaration metamodelDeclaration = grammar.getMetamodelDeclarations().get(0); XtextValidator validator = get(XtextValidator.class); ValidatingMessageAcceptor messageAcceptor = new ValidatingMessageAcceptor(metamodelDeclaration, true, false); validator.setMessageAcceptor(messageAcceptor); validator.checkGeneratedPackageNotEmpty((GeneratedMetamodel) metamodelDeclaration); messageAcceptor.validate(); }
@Test public void testConcreteLanguageToMetamodel1() throws Exception { XtextResource r = getResource("classpath:/" + ConcreteTestLanguage.class.getName().replace('.', '/') + ".xtext"); EObject element = r.getContents().get(0); Grammar g = (Grammar) element; List<AbstractMetamodelDeclaration> mms = Lists.<AbstractMetamodelDeclaration>newArrayList( Iterables.filter(g.getMetamodelDeclarations(), GeneratedMetamodel.class)); assertNotNull(mms); assertEquals(1, mms.size()); }