This repository has been archived by the owner on Apr 21, 2023. It is now read-only.
/
XtextGenerator.xtend
352 lines (313 loc) · 12 KB
/
XtextGenerator.xtend
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
/*******************************************************************************
* Copyright (c) 2015, 2017 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.xtext.generator
import com.google.common.collect.Maps
import com.google.inject.Guice
import com.google.inject.Inject
import com.google.inject.Injector
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.util.HashMap
import java.util.List
import org.eclipse.emf.common.util.URI
import org.eclipse.emf.mwe.core.WorkflowContext
import org.eclipse.emf.mwe.core.issues.Issues
import org.eclipse.emf.mwe.core.lib.AbstractWorkflowComponent2
import org.eclipse.emf.mwe.core.monitor.ProgressMonitor
import org.eclipse.emf.mwe.utils.StandaloneSetup
import org.eclipse.xtend.lib.annotations.Accessors
import org.eclipse.xtext.GeneratedMetamodel
import org.eclipse.xtext.Grammar
import org.eclipse.xtext.XtextStandaloneSetup
import org.eclipse.xtext.parser.IEncodingProvider
import org.eclipse.xtext.resource.IResourceServiceProvider
import org.eclipse.xtext.util.MergeableManifest
import org.eclipse.xtext.util.Tuples
import org.eclipse.xtext.util.internal.Log
import org.eclipse.xtext.xtext.generator.model.IXtextGeneratorFileSystemAccess
import org.eclipse.xtext.xtext.generator.model.ManifestAccess
import org.eclipse.xtext.xtext.generator.model.PluginXmlAccess
import org.eclipse.xtext.xtext.generator.model.TextFileAccess
import org.eclipse.xtext.xtext.generator.model.project.BundleProjectConfig
import org.eclipse.xtext.xtext.generator.model.project.IXtextProjectConfig
/**
* The Xtext language infrastructure generator. Use the {@code configuration} block to add general
* configuration for your Xtext project and the generated code, e.g.
* <pre>
* configuration = {
* project = model.project.StandardProjectConfig {
* baseName = "org.example.language"
* rootPath = ".."
* }
* code = {
* encoding = 'ISO-8859-1'
* }
* }
* </pre>
* You can generate code for one or more Xtext languages within the same project. For each language,
* add a {@code language} block, e.g.
* <pre>
* language = StandardLanguage {
* name = "org.example.language.MyExampleLanguage"
* }
* </pre>
*
* @noextend This class should not be extended by clients.
*/
@Log
class XtextGenerator extends AbstractWorkflowComponent2 {
@Accessors
DefaultGeneratorModule configuration = new DefaultGeneratorModule
@Accessors
val List<XtextGeneratorLanguage> languageConfigs = newArrayList
@Accessors
XtextDirectoryCleaner cleaner = new XtextDirectoryCleaner
@Accessors
XtextGeneratorStandaloneSetup standaloneSetup = new XtextGeneratorStandaloneSetup
@Accessors
String grammarEncoding
Injector injector
@Inject IXtextProjectConfig projectConfig
@Inject XtextGeneratorTemplates templates
@Inject XtextGeneratorNaming naming
@Inject CodeConfig codeConfig
new() {
new XtextStandaloneSetup().createInjectorAndDoEMFRegistration()
}
/**
* Add a language configuration to be included in the code generation process.
*/
def void addLanguage(XtextGeneratorLanguage language) {
this.languageConfigs.add(language)
}
override protected checkConfigurationInternal(org.eclipse.emf.mwe.core.issues.Issues issues) {
initialize
val generatorIssues = new MweIssues(this, issues)
configuration.checkConfiguration(generatorIssues)
val uris = new HashMap<String, Grammar>
for (language : languageConfigs) {
language.checkConfiguration(generatorIssues)
for (generatedMetamodel : language.grammar.metamodelDeclarations.filter(GeneratedMetamodel)) {
val nsURI = generatedMetamodel.EPackage.nsURI
if (uris.containsKey(nsURI)) {
generatorIssues.addError("Duplicate generated grammar with nsURI '" + nsURI + "' in "
+ uris.get(nsURI).name + " and " + language.grammar.name)
} else {
uris.put(nsURI, language.grammar)
}
}
}
}
def void initialize() {
if (injector === null) {
LOG.info('Initializing Xtext generator')
new StandaloneSetup().addRegisterGeneratedEPackage('org.eclipse.xtext.common.types.TypesPackage')
initializeEncoding
injector = createInjector
injector.injectMembers(this)
injector.getInstance(CodeConfig) => [initialize(injector)]
projectConfig.initialize(injector)
cleaner.initialize(injector)
standaloneSetup.initialize(injector)
for (language : languageConfigs) {
val languageInjector = injector.createLanguageInjector(language)
language.initialize(languageInjector)
}
}
}
protected def initializeEncoding() {
val serviceProviderRegistry = IResourceServiceProvider.Registry.INSTANCE
val serviceProvider = serviceProviderRegistry.extensionToFactoryMap.get('xtext') as IResourceServiceProvider
val encoding = grammarEncoding ?: configuration.code.encoding
if (serviceProvider !== null && encoding !== null) {
val encodingProvider = serviceProvider.get(IEncodingProvider)
if (encodingProvider instanceof IEncodingProvider.Runtime)
encodingProvider.defaultEncoding = encoding
}
}
protected def Injector createInjector() {
Guice.createInjector(configuration)
}
protected def Injector createLanguageInjector(Injector parent, XtextGeneratorLanguage language) {
parent.createChildInjector(new LanguageModule(language))
}
protected override invokeInternal(WorkflowContext ctx, ProgressMonitor monitor, org.eclipse.emf.mwe.core.issues.Issues issues) {
initialize
try {
cleaner.clean
for (language : languageConfigs) {
try {
LOG.info('Generating ' + language.grammar.name)
language.generate
language.generateSetups
language.generateModules
language.generateExecutableExtensionFactory
} catch(Exception e) {
handleException(e, issues)
}
}
LOG.info('Generating common infrastructure')
generatePluginXmls
generateManifests
generateActivator
generateServices
} catch (Exception e) {
handleException(e, issues)
}
}
private def void handleException(Exception ex, Issues issues) {
if (ex instanceof CompositeGeneratorException) {
ex.exceptions.forEach[handleException(issues)]
} else {
issues.addError(this, "GeneratorException: ", null, ex, null)
}
}
protected def generateSetups(IXtextGeneratorLanguage language) {
templates.createRuntimeGenSetup(language).writeTo(projectConfig.runtime.srcGen)
templates.createRuntimeSetup(language).writeTo(projectConfig.runtime.src)
templates.createIdeSetup(language).writeTo(projectConfig.genericIde.src)
templates.createWebSetup(language).writeTo(projectConfig.web.src)
}
protected def generateModules(IXtextGeneratorLanguage language) {
templates.createRuntimeGenModule(language).writeTo(projectConfig.runtime.srcGen)
templates.createRuntimeModule(language).writeTo(projectConfig.runtime.src)
templates.createIdeModule(language).writeTo(projectConfig.genericIde.src)
templates.createIdeGenModule(language).writeTo(projectConfig.genericIde.srcGen)
templates.createEclipsePluginGenModule(language).writeTo(projectConfig.eclipsePlugin.srcGen)
templates.createEclipsePluginModule(language).writeTo(projectConfig.eclipsePlugin.src)
templates.createIdeaGenModule(language).writeTo(projectConfig.ideaPlugin.srcGen)
templates.createIdeaModule(language).writeTo(projectConfig.ideaPlugin.src)
templates.createWebGenModule(language).writeTo(projectConfig.web.srcGen)
templates.createWebModule(language).writeTo(projectConfig.web.src)
}
protected def generateExecutableExtensionFactory(IXtextGeneratorLanguage language) {
if (projectConfig.eclipsePlugin.srcGen !== null)
templates.createEclipsePluginExecutableExtensionFactory(language, languageConfigs.head).writeTo(projectConfig.eclipsePlugin.srcGen)
}
protected def generateManifests() {
val manifests = projectConfig.enabledProjects.filter(BundleProjectConfig)
.map[Tuples.create(manifest, metaInf, name)].toList
// Filter null values and merge duplicate entries
val uri2Manifest = Maps.<URI, ManifestAccess>newHashMapWithExpectedSize(manifests.size)
val manifestIter = manifests.listIterator
while (manifestIter.hasNext) {
val entry = manifestIter.next
val manifest = entry.first
val metaInf = entry.second
if (manifest === null || metaInf === null) {
manifestIter.remove()
} else {
if (manifest.activator === null && manifest === projectConfig.eclipsePlugin.manifest) {
manifest.activator = naming.eclipsePluginActivator
}
val uri = metaInf.getURI(manifest.path)
if (uri2Manifest.containsKey(uri)) {
uri2Manifest.get(uri).merge(manifest)
manifestIter.remove()
} else {
uri2Manifest.put(uri, manifest)
}
}
}
for (entry : manifests) {
val manifest = entry.first
val metaInf = entry.second
if (manifest.bundleName === null) {
manifest.bundleName = entry.third
}
if (metaInf.isFile(manifest.path)) {
if (manifest.merge) {
mergeManifest(manifest, metaInf)
} else if (manifest.path.endsWith('.MF')) {
manifest.path = manifest.path + '_gen'
manifest.writeTo(metaInf)
}
} else {
manifest.writeTo(metaInf)
}
}
}
protected def mergeManifest(ManifestAccess manifest, IXtextGeneratorFileSystemAccess metaInf) throws IOException {
var InputStream in
try {
in = metaInf.readBinaryFile(manifest.path)
val merge = new MergeableManifest(in, manifest.bundleName)
merge.lineDelimiter = codeConfig.lineDelimiter
merge.addExportedPackages(manifest.exportedPackages)
merge.addRequiredBundles(manifest.requiredBundles)
merge.addImportedPackages(manifest.importedPackages)
if (manifest.activator !== null && merge.bundleActivator.isNullOrEmpty) {
merge.bundleActivator = manifest.activator.name
}
if (merge.isModified) {
val out = new ByteArrayOutputStream
merge.write(out)
metaInf.generateFile(manifest.path, new ByteArrayInputStream(out.toByteArray))
}
} finally {
if (in !== null)
in.close()
}
}
protected def void generateServices() {
if (projectConfig.genericIde.srcGen === null || languageConfigs.empty) {
return
}
val file = new TextFileAccess()
file.path = "META-INF/services/org.eclipse.xtext.ISetup"
file.content = '''
«FOR lang : languageConfigs»
«naming.getGenericIdeSetup(lang.grammar)»
«ENDFOR»
'''
file.writeTo(projectConfig.genericIde.srcGen)
}
protected def void generateActivator() {
if (projectConfig.eclipsePlugin.srcGen !== null && !languageConfigs.empty)
templates.createEclipsePluginActivator(projectConfig, languageConfigs).writeTo(projectConfig.eclipsePlugin.srcGen)
}
protected def void generatePluginXmls() {
val pluginXmls = projectConfig.enabledProjects.filter(BundleProjectConfig).map[pluginXml -> root].toList
// Filter null values and merge duplicate entries
val uri2PluginXml = Maps.<URI, PluginXmlAccess>newHashMapWithExpectedSize(pluginXmls.size)
val pluginXmlIter = pluginXmls.listIterator
while (pluginXmlIter.hasNext) {
val entry = pluginXmlIter.next
val pluginXml = entry.key
val root = entry.value
if (pluginXml === null || root === null) {
pluginXmlIter.remove()
} else {
val uri = root.getURI(pluginXml.path)
if (uri2PluginXml.containsKey(uri)) {
uri2PluginXml.get(uri).merge(pluginXml)
pluginXmlIter.remove()
} else {
uri2PluginXml.put(uri, pluginXml)
}
}
}
for (entry : pluginXmls) {
val pluginXml = entry.key
val root = entry.value
if (root.isFile(pluginXml.path)) {
// only write plugin.xml_gen if entries exist and content differs
if (!pluginXml.entries.isEmpty
&& root.readTextFile(pluginXml.path)?.toString != pluginXml.getContentString
&& pluginXml.path.endsWith('.xml')) {
pluginXml.path = pluginXml.path + '_gen'
pluginXml.writeTo(root)
}
} else {
pluginXml.writeTo(root)
}
}
}
}