Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 9f573d95885842b888b5449f268171ae2f0d0f3c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/**
 * Copyright (c) 2006-2012 IBM Corporation and others
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   IBM - Initial API and implementation
 */
package org.eclipse.emf.ecore.xcore.exporter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.emf.codegen.ecore.genmodel.GenBase;
import org.eclipse.emf.codegen.ecore.genmodel.GenClassifier;
import org.eclipse.emf.codegen.ecore.genmodel.GenFeature;
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
import org.eclipse.emf.codegen.ecore.genmodel.GenModelFactory;
import org.eclipse.emf.codegen.ecore.genmodel.GenModelPackage;
import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
import org.eclipse.emf.codegen.util.ImportManager;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.Monitor;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EGenericType;
import org.eclipse.emf.ecore.EModelElement;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xcore.XGenericType;
import org.eclipse.emf.ecore.xcore.XImportDirective;
import org.eclipse.emf.ecore.xcore.XPackage;
import org.eclipse.emf.ecore.xcore.XReference;
import org.eclipse.emf.ecore.xcore.XcoreFactory;
import org.eclipse.emf.ecore.xcore.XcorePackage;
import org.eclipse.emf.ecore.xcore.mappings.XcoreMapper;
import org.eclipse.emf.ecore.xcore.scoping.XcoreImportedNamespaceAwareScopeProvider;
import org.eclipse.emf.ecore.xcore.util.EcoreXcoreBuilder;
import org.eclipse.emf.ecore.xcore.util.XcoreGenModelBuilder;
import org.eclipse.emf.ecore.xcore.util.XcoreGenModelInitializer;
import org.eclipse.emf.exporter.ModelExporter;
import org.eclipse.xtext.naming.IQualifiedNameConverter;
import org.eclipse.xtext.naming.IQualifiedNameProvider;
import org.eclipse.xtext.naming.QualifiedName;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.SaveOptions;
import org.eclipse.xtext.scoping.IScope;
import org.eclipse.xtext.scoping.IScopeProvider;
import org.eclipse.xtext.ui.XtextProjectHelper;

import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.Provider;

public class XcoreExporter extends ModelExporter
{
  @Inject
  Provider<EcoreXcoreBuilder> ecoreXcoreBuilderProvider;

  @Inject
  XcoreGenModelBuilder genModelBuilder;

  @Inject
  XcoreGenModelInitializer genModelInitializer;

  @Inject
  XcoreMapper mapper;

  @Inject
  private IScopeProvider scopeProvider;

  @Inject
  private IQualifiedNameProvider qualifiedNameProvider;

  @Inject
  private IQualifiedNameConverter qualifiedNameConverter;


  private static final Set<String> IMPLICIT_ALIASES = Sets.newHashSet();
  static
  {
    for (EDataType eDataType : XcoreImportedNamespaceAwareScopeProvider.IMPLICIT_ALIASES)
    {
      IMPLICIT_ALIASES.add("org.eclipse.emf.ecore." + eDataType.getName());
    }
  }

  @Override
  public String getID()
  {
    return "org.eclipse.emf.ecore.xcore.exporter";
  }

  @Override
  public void dispose()
  {
    super.dispose();
  }

  @Override
  protected String getDefaultArtifactLocation(EPackage ePackage)
  {
    return getEPackageToGenPackageMap().get(ePackage).getPrefix() + ".xcore";
  }

  @Override
  protected String doCheckEPackageArtifactLocation(String location, String packageName)
  {
    if (!location.endsWith(".xcore"))
    {
      return XcoreExporterPlugin.INSTANCE.getString("_UI_InvalidArtifactFileNameExtension_message");
    }
    return super.doCheckEPackageArtifactLocation(location, packageName);
  }

  @Override
  protected Diagnostic doExport(Monitor monitor, ModelExporter.ExportData exportData) throws Exception
  {
    for (Map.Entry<GenPackage, URI> entry : exportData.genPackageToArtifactURI.entrySet())
    {
      GenPackage genPackage = entry.getKey();
      URI xcoreLocationURI = entry.getValue();

      // Add the Xtext nature if it's absent.
      //
      IFile xcoreFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(xcoreLocationURI.toPlatformString(true)));
      final IProject xcoreProject = xcoreFile.getProject();
      if (xcoreProject.isAccessible())
      {
        if (!xcoreProject.hasNature(XtextProjectHelper.NATURE_ID))
        {
          IProjectDescription description = xcoreProject.getDescription();
          String[] natures = description.getNatureIds();
          String[] newNatures = new String[natures.length + 1];
          System.arraycopy(natures, 0, newNatures, 0, natures.length);
          newNatures[natures.length] = XtextProjectHelper.NATURE_ID;
          description.setNatureIds(newNatures);
          xcoreProject.setDescription(description, null);
        }
      }

      // Create an appropriate resource set for Xcore models.
      //
      final ResourceSet resourceSet = new ResourceSetImpl();
      resourceSet.getURIConverter().getURIMap().putAll(EcorePlugin.computePlatformURIMap(true));

      // Load a clone of the GenModel in the new resource set.
      //
      GenModel inputGenModel = (GenModel)resourceSet.getEObject(EcoreUtil.getURI(getGenModel()), true);
      inputGenModel.reconcile();

      Resource inputResource = inputGenModel.eResource();
      final Resource outputResource = resourceSet.createResource(xcoreLocationURI);

      // Create a fresh newly GenModel for the packages we just loaded.
      //
      GenModel genModel = GenModelFactory.eINSTANCE.createGenModel();
      List<EPackage> ePackageClones = new ArrayList<EPackage>();
      for (GenPackage inputGenPackage : inputGenModel.getGenPackages())
      {
        ePackageClones.add(inputGenPackage.getEcorePackage());
      }
      genModel.initialize(ePackageClones);

      // Add it to the resource and initialize it like we do any other new GenModel
      //
      inputResource.getContents().add(genModel);
      genModelInitializer.initialize(genModel, true);

      // Walk the two GenModels in lockstep and compare settings.
      // We need to know which ones should be converted to annotations and which would be redundant because they represent defaults.
      //
      final GenPackage inputGenPackage = (GenPackage)resourceSet.getEObject(EcoreUtil.getURI(genPackage), true);
      new Object()
      {
        void visit(GenBase genBase1, GenBase genBase2)
        {
          if (genBase1.eClass() == genBase2.eClass())
          {
            // TODO handle multi-valued attribues and references.
            //
            for (EAttribute eAttribute : genBase1.eClass().getEAllAttributes())
            {
              if (!eAttribute.isMany() && genBase1.eIsSet(eAttribute))
              {
                Object value1 = genBase1.eGet(eAttribute);
                Object value2 = genBase2.eGet(eAttribute);
                if (value1 == null ? value2 != null : !value1.equals(value2))
                {
                  // For the case of the GenModel, we record its annotations on the package.
                  //
                  EModelElement eModelElement = genBase2.getEcoreModelElement();
                  if (eModelElement == null && genBase2 instanceof GenModel)
                  {
                    eModelElement = inputGenPackage.getEcorePackage();
                  }
                  EcoreUtil.setAnnotation(eModelElement, GenModelPackage.eNS_URI, eAttribute.getName(), EcoreUtil.convertToString(eAttribute.getEAttributeType(), value1));
                }
                for (Iterator<EObject> i = genBase1.eContents().iterator(), j = genBase2.eContents().iterator(); i.hasNext() && j.hasNext();)
                {
                  EObject content1 = i.next();
                  EObject content2 = j.next();
                  if (content1 instanceof GenBase && content2 instanceof GenBase)
                  {
                    visit((GenBase)content1, (GenBase)content2);
                  }
                }
              }
            }
          }
        }
      }.visit(inputGenModel, genModel);

      // Use the builder to create an appropriate Xcore instance for populating the output resource.
      //
      EcoreXcoreBuilder ecoreXcoreBuilder = ecoreXcoreBuilderProvider.get();
      ecoreXcoreBuilder.initialize(inputGenModel);
      XPackage xPackage = ecoreXcoreBuilder.getXPackage(inputGenPackage.getEcorePackage());
      outputResource.getContents().add(xPackage);
      outputResource.getContents().add(inputGenModel);
      outputResource.getContents().add(inputGenPackage.getEcorePackage());

      // Put all the specialize internal GenPackages in appropriately named resources so the serialize can resolve them.
      //
      GenPackage ecoreGenPackage = inputGenModel.getEcoreGenPackage();
      if (ecoreGenPackage != null)
      {
        Resource ecoreResource = resourceSet.createResource(URI.createPlatformResourceURI("/org.eclipse.emf.ecore/model/Ecore.genmodel", false));
        ecoreResource.getContents().add(ecoreGenPackage.getGenModel());
      }
      GenPackage xmlTypeGenPackage = inputGenModel.getXMLTypeGenPackage();
      if (xmlTypeGenPackage != null)
      {
        Resource xmlTypeResource = resourceSet.createResource(URI.createPlatformResourceURI("/org.eclipse.emf.ecore/model/XMLType.genmodel", false));
        xmlTypeResource.getContents().add(xmlTypeGenPackage.getGenModel());
      }
      GenPackage xmlNamespaceGenPackage = inputGenModel.getXMLNamespaceGenPackage();
      if (xmlNamespaceGenPackage != null)
      {
        Resource xmlNamespaceResource = resourceSet.createResource(URI.createPlatformResourceURI("/org.eclipse.emf.ecore/model/XMLNamespace.genmodel", false));
        xmlNamespaceResource.getContents().add(xmlNamespaceGenPackage.getGenModel());
      }

      resourceSet.getURIConverter().getURIMap().remove(URI.createPlatformResourceURI("/org.eclipse.emf.ecore/", false));

      // Do the final linking step and build the map.
      //
      ecoreXcoreBuilder.link();
      genModelBuilder.buildMap(inputGenModel);

      // Use an import manager to create imports for all the things we reference in the Xcore instance.
      //
      ImportManager importManager =
        new ImportManager(inputGenPackage.getInterfacePackageName())
        {
          @Override
          protected boolean shouldImport(String packageName, String shortName, String importName)
          {
            return true;
          }
        };
      Map<EGenericType, XGenericType> genericTypeMap = ecoreXcoreBuilder.getGenericTypeMap();
      for (TreeIterator<EObject> i = inputGenPackage.getEcorePackage().eAllContents(); i.hasNext();)
      {
        EObject eObject = i.next();
        if (eObject instanceof EGenericType)
        {
          EGenericType eGenericType = (EGenericType)eObject;
          EClassifier eClassifier = eGenericType.getEClassifier();
          if (eClassifier != null)
          {
            GenClassifier genClassifier = inputGenModel.findGenClassifier(eClassifier);
            QualifiedName qualifiedName = qualifiedNameProvider.getFullyQualifiedName(genClassifier);
            String qualifiedNameValue = qualifiedNameConverter.toString(qualifiedName);
            if (!IMPLICIT_ALIASES.contains(qualifiedNameValue))
            {
              importManager.addImport(qualifiedNameValue);
            }

            // We need to ensure that if we resolve to a different instance, we switch to use that so that serialization will find the right instance.
            //
            XGenericType xGenericType = genericTypeMap.get(eGenericType);
            IScope scope = scopeProvider.getScope(xGenericType, XcorePackage.Literals.XGENERIC_TYPE__TYPE);
            IEObjectDescription genClassifierDescription = scope.getSingleElement(qualifiedName);
            if (genClassifierDescription != null)
            {
              EObject resolvedGenClassifier = resourceSet.getEObject(genClassifierDescription.getEObjectURI(), true);
              if (resolvedGenClassifier != null && resolvedGenClassifier != genClassifier)
              {
                xGenericType.setType((GenClassifier)resolvedGenClassifier);
              }
            }
          }
        }
        else if (eObject instanceof EReference)
        {
          EReference eReference = (EReference)eObject;
          XReference xReference = (XReference)mapper.getToXcoreMapping(eReference).getXcoreElement();
          EList<GenFeature> keys = xReference.getKeys();
          GenFeature opposite = xReference.getOpposite();
          if (opposite != null)
          {
            IScope scope = scopeProvider.getScope(xReference, XcorePackage.Literals.XREFERENCE__OPPOSITE);
            IEObjectDescription genFeatureDescription = scope.getSingleElement(QualifiedName.create(opposite.getName()));
            if (genFeatureDescription != null)
            {
              EObject resolvedGenFeature = resourceSet.getEObject(genFeatureDescription.getEObjectURI(), true);
              if (resolvedGenFeature != null)
              {
                xReference.setOpposite((GenFeature)resolvedGenFeature);
              }
            }
          }
          if (!keys.isEmpty())
          {
            IScope scope = scopeProvider.getScope(xReference, XcorePackage.Literals.XREFERENCE__KEYS);
            for (ListIterator<GenFeature> k = keys.listIterator(); k.hasNext(); )
            {
              GenFeature key = k.next();
              IEObjectDescription genFeatureDescription = scope.getSingleElement(QualifiedName.create(key.getName()));
              if (genFeatureDescription != null)
              {
                EObject resolvedGenFeature = resourceSet.getEObject(genFeatureDescription.getEObjectURI(), true);
                if (resolvedGenFeature != null)
                {
                  k.set((GenFeature)resolvedGenFeature);
                }
              }
            }
          }
        }
        else if (eObject instanceof EPackage)
        {
          i.prune();
        }
      }

      // Convert the needed imports to import directives.
      //
      for (String qualifiedName : importManager.getImports())
      {
        XImportDirective xImportDirective = XcoreFactory.eINSTANCE.createXImportDirective();
        xImportDirective.setImportedNamespace(qualifiedName);
        xPackage.getImportDirectives().add(xImportDirective);
      }

      // Save the final result.
      //
      final Map<Object, Object> options = new HashMap<Object, Object>();
      SaveOptions.newBuilder().format().noValidation().getOptions().addTo(options);

      // Do this is a job so that Xtext nature we added as a chance to build the index needed by the serializer.
      //
      Job job =
        new Job("Save")
        {
          @Override
          protected IStatus run(IProgressMonitor monitor)
          {
            try
            {
              // Temporarily clear the mappings so that the serializer properly finds the non-normalized URIs in the index.
              //
              Map<URI, URI> uriMap = resourceSet.getURIConverter().getURIMap();
              Map<URI, URI> copyiedURIMap = new HashMap<URI, URI>(uriMap);
              uriMap.clear();
              outputResource.save(options);
              uriMap.putAll(copyiedURIMap);
            }
            catch (IOException exception)
            {
              return Status.CANCEL_STATUS;
            }
            return Status.OK_STATUS;
          }
        };
      job.schedule();
    }
    return Diagnostic.OK_INSTANCE;
  }

  protected URI getReferencedGenPackageArtifactURI(ModelExporter.ExportData exportData, GenPackage genPackage)
  {
    URI artifactURI = exportData.referencedGenPackagesToArtifactURI.get(genPackage);
    if (artifactURI == null)
    {
      artifactURI = exportData.genPackageToArtifactURI.get(genPackage);
      if (artifactURI == null)
      {
        for (Map.Entry<GenPackage, URI> entry : exportData.referencedGenPackagesToArtifactURI.entrySet())
        {
          GenPackage referencedGenPackage = entry.getKey();
          if (genPackage.getNSURI().equals(referencedGenPackage.getNSURI()) &&
                genPackage.getEcorePackage().getName().equals(referencedGenPackage.getEcorePackage().getName()))
          {
            artifactURI = entry.getValue();
          }
        }
      }
    }
    return artifactURI;
  }

  @Override
  protected void adjustGenModel()
  {
    // Ignore all packages not actually contained in the GenModel.
    // We don't need information about where referenced GenPackages are located.
    //
    GenModel genModel = getGenModel();
    for (ListIterator<EPackage> i = getEPackages().listIterator(); i.hasNext();)
    {
      if (!EcoreUtil.isAncestor(genModel, getEPackageToGenPackageMap().get(i.next())))
      {
        i.remove();
      }
    }
    super.adjustGenModel();
  }
}

Back to the top