-
Notifications
You must be signed in to change notification settings - Fork 3
/
AqlQuickFixesSwitch.java
718 lines (646 loc) · 27.5 KB
/
AqlQuickFixesSwitch.java
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
/*******************************************************************************
* Copyright (c) 2023, 2024 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.aql.validation.quickfixes;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.acceleo.AcceleoPackage;
import org.eclipse.acceleo.Binding;
import org.eclipse.acceleo.Block;
import org.eclipse.acceleo.ErrorImport;
import org.eclipse.acceleo.ErrorModuleReference;
import org.eclipse.acceleo.Import;
import org.eclipse.acceleo.LetStatement;
import org.eclipse.acceleo.Metamodel;
import org.eclipse.acceleo.Module;
import org.eclipse.acceleo.ModuleElement;
import org.eclipse.acceleo.Query;
import org.eclipse.acceleo.Statement;
import org.eclipse.acceleo.Template;
import org.eclipse.acceleo.TextStatement;
import org.eclipse.acceleo.Variable;
import org.eclipse.acceleo.VisibilityKind;
import org.eclipse.acceleo.aql.AcceleoUtil;
import org.eclipse.acceleo.aql.parser.AcceleoAstSerializer;
import org.eclipse.acceleo.aql.parser.AcceleoParser;
import org.eclipse.acceleo.aql.validation.IAcceleoValidationResult;
import org.eclipse.acceleo.query.AQLUtils;
import org.eclipse.acceleo.query.ast.ASTNode;
import org.eclipse.acceleo.query.ast.Call;
import org.eclipse.acceleo.query.ast.CallType;
import org.eclipse.acceleo.query.ast.EClassifierTypeLiteral;
import org.eclipse.acceleo.query.ast.EnumLiteral;
import org.eclipse.acceleo.query.ast.ErrorCall;
import org.eclipse.acceleo.query.ast.Expression;
import org.eclipse.acceleo.query.ast.VarRef;
import org.eclipse.acceleo.query.parser.AstResult;
import org.eclipse.acceleo.query.parser.AstSerializer;
import org.eclipse.acceleo.query.parser.CombineIterator;
import org.eclipse.acceleo.query.parser.Positions;
import org.eclipse.acceleo.query.parser.quickfixes.AstQuickFix;
import org.eclipse.acceleo.query.parser.quickfixes.AstQuickFixesSwitch;
import org.eclipse.acceleo.query.parser.quickfixes.AstTextReplacement;
import org.eclipse.acceleo.query.parser.quickfixes.IAstQuickFix;
import org.eclipse.acceleo.query.parser.quickfixes.IAstTextReplacement;
import org.eclipse.acceleo.query.runtime.namespace.IQualifiedNameQueryEnvironment;
import org.eclipse.acceleo.query.runtime.namespace.IQualifiedNameResolver;
import org.eclipse.acceleo.query.validation.type.ClassType;
import org.eclipse.acceleo.query.validation.type.EClassifierType;
import org.eclipse.acceleo.query.validation.type.ICollectionType;
import org.eclipse.acceleo.query.validation.type.IType;
import org.eclipse.acceleo.query.validation.type.SetType;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EPackage;
public class AqlQuickFixesSwitch extends AstQuickFixesSwitch {
/**
* A space.
*/
private static final String SPACE = " ";
/**
* The {@link Pattern} to find empty module metamodel part of the {@link Module}.
*/
private static final Pattern EMPTY_MODULE_METAMODEL_PATTERN = Pattern.compile("\\(\\s*\\)");
/**
* The {@link Pattern} to find empty parameter part of a {@link Template} or {@link Query}.
*/
private static final Pattern EMPTY_PARAMETER_PATTERN = Pattern.compile("\\(\\s*\\)");
/**
* The {@link IQualifiedNameQueryEnvironment}.
*/
private final IQualifiedNameQueryEnvironment queryEnvironment;
/**
* The {@link IAcceleoValidationResult}.
*/
private IAcceleoValidationResult validationResult;
/**
* the {@link Module}.
*/
private final Module module;
/**
* The {@link Module} qualified name.
*/
private String moduleQualifiedName;
/**
* the text representation of the {@link Module}.
*/
private String moduleText;
/**
* Line and column for each offset in {@link #moduleText}.
*/
final int[][] linesAndColumns;
/**
* The {@link Positions}.
*/
private final Positions<ASTNode> positions;
/**
* The new line {@link String}.
*/
private final String newLine;
/**
* Constructor.
*
* @param queryEnvironment
* the {@link IQualifiedNameQueryEnvironment}.
* @param validationResult
* the {@link IAcceleoValidationResult}
* @param moduleQualifiedName
* the {@link Module} qualified name
* @param moduleText
* the text representation of the {@link Module}
* @param newLine
* the new line {@link String}
*/
public AqlQuickFixesSwitch(IQualifiedNameQueryEnvironment queryEnvironment,
IAcceleoValidationResult validationResult, String moduleQualifiedName, String moduleText,
String newLine) {
super(validationResult.getAcceleoAstResult().getPositions());
this.queryEnvironment = queryEnvironment;
this.validationResult = validationResult;
this.module = validationResult.getAcceleoAstResult().getModule();
this.moduleQualifiedName = moduleQualifiedName;
this.moduleText = moduleText;
this.linesAndColumns = AQLUtils.getLinesAndColumns(moduleText);
this.newLine = newLine;
this.positions = validationResult.getAcceleoAstResult().getPositions();
}
@Override
public List<IAstQuickFix> caseVarRef(VarRef varRef) {
final List<IAstQuickFix> res = new ArrayList<>();
final ModuleElement moduleElement = AcceleoUtil.getContainingModuleElement(varRef);
if (moduleElement != null) {
res.addAll(getAddParameterQuickFixes(varRef, moduleElement));
}
// add surrounding LetStatement
final Statement containingStatement = AcceleoUtil.getContainingStatement(varRef);
if (containingStatement != null) {
res.addAll(getSurroundWithLetStatementQuickFix(varRef, containingStatement));
}
return res;
}
private List<IAstQuickFix> getSurroundWithLetStatementQuickFix(VarRef varRef,
final Statement containingStatement) {
final List<IAstQuickFix> res = new ArrayList<>();
final IQualifiedNameResolver resolver = queryEnvironment.getLookupEngine().getResolver();
final URI uri = resolver.getSourceURI(moduleQualifiedName);
final LetStatement letStatement = AcceleoPackage.eINSTANCE.getAcceleoFactory().createLetStatement();
final Block body = AcceleoPackage.eINSTANCE.getAcceleoFactory().createBlock();
final TextStatement textStatement = AcceleoPackage.eINSTANCE.getAcceleoFactory()
.createTextStatement();
final int offsetStart = positions.getStartPositions(containingStatement);
final int lineStart = positions.getStartLines(containingStatement);
final int columnStart = positions.getStartColumns(containingStatement);
final int offsetEnd = positions.getEndPositions(containingStatement);
final int lineEnd = positions.getEndLines(containingStatement);
final int columnEnd = positions.getEndColumns(containingStatement);
// use a TextStatement to serialize exactly the original code
final String indent = moduleText.substring(offsetStart - columnStart, offsetStart);
final String text = indent + moduleText.substring(positions.getStartPositions(containingStatement),
positions.getEndPositions(containingStatement)).replaceAll("\\R\\s*", "$0" + SPACE + SPACE)
+ newLine + indent;
textStatement.setValue(text);
body.getStatements().add(textStatement);
letStatement.setBody(body);
final Binding binding = AcceleoPackage.eINSTANCE.getAcceleoFactory().createBinding();
binding.setName(varRef.getVariableName());
final AstResult bindingType = parseWhileAqlTypeLiteral(AstSerializer.STRING_TYPE);
binding.setType(bindingType);
binding.setTypeAql(bindingType.getAst());
final org.eclipse.acceleo.Expression initExpression = AcceleoPackage.eINSTANCE.getAcceleoFactory()
.createExpression();
final AstResult initExpressionAstResult = parseWhileAqlExpression("''");
initExpression.setAst(initExpressionAstResult);
initExpression.setAql(initExpressionAstResult.getAst());
binding.setInitExpression(initExpression);
letStatement.getVariables().add(binding);
final IAstQuickFix fix = new AstQuickFix("Surround with Let: " + varRef.getVariableName());
final String replacement = new AcceleoAstSerializer(newLine).serialize(letStatement);
final AstTextReplacement textReplacement = new AstTextReplacement(uri, replacement, offsetStart,
lineStart, columnStart, offsetEnd, lineEnd, columnEnd);
fix.getTextReplacements().add(textReplacement);
res.add(fix);
return res;
}
private List<IAstQuickFix> getAddParameterQuickFixes(VarRef varRef, final ModuleElement moduleElement) {
final List<IAstQuickFix> res = new ArrayList<>();
final IAstQuickFix fix = new AstQuickFix("Add parameter " + varRef.getVariableName());
final IQualifiedNameResolver resolver = queryEnvironment.getLookupEngine().getResolver();
final URI uri = resolver.getSourceURI(moduleQualifiedName);
if (moduleElement instanceof Template) {
final Template template = (Template)moduleElement;
if (!template.getParameters().isEmpty()) {
final Variable lastParameter = template.getParameters().get(template.getParameters().size()
- 1);
final int offset = positions.getEndPositions(lastParameter);
final int line = positions.getEndLines(lastParameter);
final int column = positions.getEndColumns(lastParameter);
final AstTextReplacement textReplacement = new AstTextReplacement(uri, AcceleoParser.COMMA
+ SPACE + varRef.getVariableName() + AcceleoParser.COLON + SPACE
+ AstSerializer.STRING_TYPE, offset, line, column, offset, line, column);
fix.getTextReplacements().add(textReplacement);
res.add(fix);
} else {
final int templateStartOffest = positions.getStartPositions(template);
final Matcher matcher = EMPTY_PARAMETER_PATTERN.matcher(moduleText.substring(
templateStartOffest, positions.getEndPositions(template)));
if (matcher.find()) {
final int offset = templateStartOffest + matcher.start();
final int line = linesAndColumns[offset][0];
final int column = linesAndColumns[offset][1];
final AstTextReplacement textReplacement = new AstTextReplacement(uri, varRef
.getVariableName() + AcceleoParser.COLON + SPACE + AstSerializer.STRING_TYPE,
offset, line, column, offset, line, column);
fix.getTextReplacements().add(textReplacement);
res.add(fix);
}
}
} else if (moduleElement instanceof Query) {
final Query query = (Query)moduleElement;
if (!query.getParameters().isEmpty()) {
final Variable lastParameter = query.getParameters().get(query.getParameters().size() - 1);
final int offset = positions.getEndPositions(lastParameter);
final int line = positions.getEndLines(lastParameter);
final int column = positions.getEndColumns(lastParameter);
final AstTextReplacement textReplacement = new AstTextReplacement(uri, AcceleoParser.COMMA
+ SPACE + varRef.getVariableName() + AcceleoParser.COLON + SPACE
+ AstSerializer.STRING_TYPE, offset, line, column, offset, line, column);
fix.getTextReplacements().add(textReplacement);
res.add(fix);
} else {
final int queryStartOffest = positions.getStartPositions(query);
final Matcher matcher = EMPTY_PARAMETER_PATTERN.matcher(moduleText.substring(queryStartOffest,
positions.getEndPositions(query)));
if (matcher.find()) {
final int offset = queryStartOffest + matcher.start();
final int line = linesAndColumns[offset][0];
final int column = linesAndColumns[offset][1];
final AstTextReplacement textReplacement = new AstTextReplacement(uri, varRef
.getVariableName() + AcceleoParser.COLON + SPACE + AstSerializer.STRING_TYPE,
offset, line, column, offset, line, column);
fix.getTextReplacements().add(textReplacement);
res.add(fix);
}
}
}
return res;
}
@Override
public List<IAstQuickFix> caseErrorCall(ErrorCall errorCall) {
final List<IAstQuickFix> res = new ArrayList<>();
if (errorCall.isMissingEndParenthesis()) {
final IAstQuickFix fix = new AstQuickFix("Add missing closing parenthesis");
final IQualifiedNameResolver resolver = queryEnvironment.getLookupEngine().getResolver();
final URI uri = resolver.getSourceURI(moduleQualifiedName);
final int offset = positions.getEndPositions(errorCall);
final int line = positions.getEndLines(errorCall);
final int column = positions.getEndColumns(errorCall);
final AstTextReplacement textReplacement = new AstTextReplacement(uri, ")", offset, line, column,
offset, line, column);
fix.getTextReplacements().add(textReplacement);
res.add(fix);
}
return res;
}
@Override
public List<IAstQuickFix> caseCall(Call call) {
final List<IAstQuickFix> res = new ArrayList<>();
final IType returnType = new ClassType(queryEnvironment, String.class);
final List<Set<IType>> argumentTypes = getArgumentPossibleTypes(call);
final CombineIterator<IType> combineIt = new CombineIterator<>(argumentTypes);
while (combineIt.hasNext()) {
res.addAll(getAddServiceQuickFixes(call.getServiceName(), returnType, combineIt.next()));
}
return res;
}
/**
* Gets the argument possible {@link IType} for the given {@link Call}.
*
* @param call
* the {@link Call}
* @return the argument possible {@link IType} for the given {@link Call}
*/
private List<Set<IType>> getArgumentPossibleTypes(Call call) {
final List<Set<IType>> res = new ArrayList<>();
final Iterator<Expression> it = call.getArguments().iterator();
final Expression receiver = it.next();
final Set<IType> receiverPossibleTypes = validationResult.getPossibleTypes(receiver);
if (call.getType() == CallType.COLLECTIONCALL) {
final Set<IType> receiverCollectionTypes = new LinkedHashSet<>();
for (IType receiverPossibleType : receiverPossibleTypes) {
if (receiverPossibleType instanceof ICollectionType) {
receiverCollectionTypes.add(receiverPossibleType);
} else {
receiverCollectionTypes.add(new SetType(queryEnvironment, receiverPossibleType));
}
}
res.add(receiverCollectionTypes);
} else {
final Set<IType> receiverRawTypes = new LinkedHashSet<>();
for (IType receiverPossibleType : receiverPossibleTypes) {
if (receiverPossibleType instanceof ICollectionType) {
receiverRawTypes.add(((ICollectionType)receiverPossibleType).getCollectionType());
} else {
receiverRawTypes.add(receiverPossibleType);
}
}
res.add(receiverRawTypes);
}
while (it.hasNext()) {
final Expression argument = it.next();
res.add(validationResult.getPossibleTypes(argument));
}
return res;
}
@Override
public List<IAstQuickFix> caseEClassifierTypeLiteral(EClassifierTypeLiteral eClassifierTypeLiteral) {
final List<IAstQuickFix> res;
final String ePackageName = eClassifierTypeLiteral.getEPackageName();
if (queryEnvironment.getEPackageProvider().getEPackage(ePackageName).isEmpty()) {
res = getAddMetamodelsQuickFixes(ePackageName);
} else {
res = Collections.emptyList();
}
return res;
}
@Override
public List<IAstQuickFix> caseEnumLiteral(EnumLiteral enumLiteral) {
final List<IAstQuickFix> res;
final String ePackageName = enumLiteral.getEPackageName();
if (queryEnvironment.getEPackageProvider().getEPackage(ePackageName).isEmpty()) {
res = getAddMetamodelsQuickFixes(ePackageName);
} else {
res = Collections.emptyList();
}
return res;
}
/**
* Gets the {@link List} of {@link IAstQuickFix} to add needed metamodels according to the given
* {@link EPackage#getName() EPackage name}.
*
* @param ePackageName
* the {@link EPackage#getName() EPackage name}
* @return the {@link List} of {@link IAstQuickFix} to add needed metamodels according to the given
* {@link EPackage#getName() EPackage name}
*/
private List<IAstQuickFix> getAddMetamodelsQuickFixes(final String ePackageName) {
final List<IAstQuickFix> res = new ArrayList<>();
final IQualifiedNameResolver resolver = queryEnvironment.getLookupEngine().getResolver();
final URI uri = resolver.getSourceURI(moduleQualifiedName);
for (Object obj : EPackage.Registry.INSTANCE.values()) {
final EPackage ePkg;
if (obj instanceof EPackage.Descriptor) {
ePkg = ((EPackage.Descriptor)obj).getEPackage();
} else if (obj instanceof EPackage) {
ePkg = (EPackage)obj;
} else {
// this should not happen
continue;
}
if (ePkg.getName().equals(ePackageName)) {
final IAstQuickFix fix = new AstQuickFix("Add " + ePkg.getNsURI());
final int offset;
final int line;
final int column;
if (module.getMetamodels().isEmpty()) {
final String moduleHeader = moduleText.substring(module.getStartHeaderPosition(), module
.getEndHeaderPosition());
final Matcher matcher = EMPTY_MODULE_METAMODEL_PATTERN.matcher(moduleHeader);
if (matcher.find()) {
offset = module.getStartHeaderPosition() + matcher.start();
line = linesAndColumns[offset][0];
column = linesAndColumns[offset][1];
final AstTextReplacement textReplacement = new AstTextReplacement(uri,
AcceleoParser.QUOTE + ePkg.getNsURI() + AcceleoParser.QUOTE, offset, line,
column, offset, line, column);
fix.getTextReplacements().add(textReplacement);
res.add(fix);
}
} else {
final Metamodel lastMetamodel = module.getMetamodels().get(module.getMetamodels().size()
- 1);
offset = positions.getEndPositions(lastMetamodel);
line = positions.getEndLines(lastMetamodel);
column = positions.getEndColumns(lastMetamodel);
final AstTextReplacement textReplacement = new AstTextReplacement(uri, AcceleoParser.COMMA
+ SPACE + AcceleoParser.QUOTE + ePkg.getNsURI() + AcceleoParser.QUOTE, offset,
line, column, offset, line, column);
fix.getTextReplacements().add(textReplacement);
res.add(fix);
}
}
}
return res;
}
private List<IAstQuickFix> getAddServiceQuickFixes(String serviceName, IType returnType,
List<IType> argumentTypes) {
final List<IAstQuickFix> res = new ArrayList<>();
final String signature = getSignature(serviceName, argumentTypes);
final IQualifiedNameResolver resolver = queryEnvironment.getLookupEngine().getResolver();
final URI uri = resolver.getSourceURI(moduleQualifiedName);
if (isQueryModule(moduleQualifiedName)) {
final IAstQuickFix fix = new AstQuickFix("Add query " + signature + " to this module");
if (uri != null && "file".equals(uri.getScheme())) {
fix.getTextReplacements().add(getQueryReplacement(uri, module, serviceName, returnType,
argumentTypes));
}
res.add(fix);
} else {
final IAstQuickFix fix = new AstQuickFix("Add template " + signature + " to this module");
if (uri != null && "file".equals(uri.getScheme())) {
fix.getTextReplacements().add(getTemplateReplacement(uri, module, serviceName, returnType,
argumentTypes));
}
res.add(fix);
}
final List<String> qualifiedNames = new ArrayList<>();
if (module.getExtends() != null && !(module.getExtends() instanceof ErrorModuleReference)) {
qualifiedNames.add(module.getExtends().getQualifiedName());
}
for (Import imp : module.getImports()) {
if (!(imp instanceof ErrorImport)) {
if (!(imp.getModule() instanceof ErrorModuleReference) && validationResult
.getValidationMessages(imp.getModule()).isEmpty()) {
qualifiedNames.add(imp.getModule().getQualifiedName());
}
}
}
for (String qName : qualifiedNames) {
final Object resolved = resolver.resolve(qName);
if (resolved instanceof Module) {
if (isQueryModule(qName)) {
final IAstQuickFix fix = new AstQuickFix("Add query " + signature + " to " + qName);
final URI sourceURI = resolver.getSourceURI(qName);
if (sourceURI != null && "file".equals(sourceURI.getScheme())) {
fix.getTextReplacements().add(getQueryReplacement(sourceURI, (Module)resolved,
serviceName, returnType, argumentTypes));
}
res.add(fix);
} else {
final IAstQuickFix fix = new AstQuickFix("Add template " + signature + " to " + qName);
final URI sourceURI = resolver.getSourceURI(qName);
if (sourceURI != null && "file".equals(sourceURI.getScheme())) {
fix.getTextReplacements().add(getTemplateReplacement(sourceURI, (Module)resolved,
serviceName, returnType, argumentTypes));
}
res.add(fix);
}
} else if (resolved instanceof Class<?>) {
final URI sourceURI = resolver.getSourceURI(qName);
if (sourceURI != null && "file".equals(sourceURI.getScheme())) {
final IAstQuickFix fix = new AstQuickFix("Add service " + signature + " to " + qName);
try (InputStream is = sourceURI.toURL().openStream()) {
final String classContents = AcceleoUtil.getContent(is, StandardCharsets.UTF_8
.name());
fix.getTextReplacements().add(getServiceReplacement(sourceURI, (Class<?>)resolved,
classContents, serviceName, returnType, argumentTypes));
res.add(fix);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return res;
}
private IAstTextReplacement getQueryReplacement(URI sourceURI, Module module, String serviceName,
IType returnType, List<IType> argumentTypes) {
final Query query = AcceleoPackage.eINSTANCE.getAcceleoFactory().createQuery();
query.setVisibility(VisibilityKind.PUBLIC);
query.setName(serviceName);
query.setType(parseWhileAqlTypeLiteral(getAqlTypeString(returnType)));
org.eclipse.acceleo.Expression body = AcceleoPackage.eINSTANCE.getAcceleoFactory().createExpression();
body.setAst(parseWhileAqlExpression("null"));
query.setBody(body);
int i = 0;
for (IType type : argumentTypes) {
final Variable parameter = AcceleoPackage.eINSTANCE.getAcceleoFactory().createVariable();
parameter.setName("parameter" + i++);
parameter.setType(parseWhileAqlTypeLiteral(getAqlTypeString(type)));
query.getParameters().add(parameter);
}
final int offset = module.getAst().getEndPosition(module);
final int line = module.getAst().getEndLine(module);
final int column = module.getAst().getEndColumn(module);
final String replacement;
if (column != 0) {
replacement = newLine + newLine + new AcceleoAstSerializer(newLine).serialize(query);
} else {
replacement = newLine + new AcceleoAstSerializer(newLine).serialize(query);
}
final IAstTextReplacement res = new AstTextReplacement(sourceURI, replacement, offset, line, column,
offset, line, column);
return res;
}
private IAstTextReplacement getTemplateReplacement(URI sourceURI, Module module, String serviceName,
IType returnType, List<IType> argumentTypes) {
final Template template = AcceleoPackage.eINSTANCE.getAcceleoFactory().createTemplate();
template.setVisibility(VisibilityKind.PUBLIC);
template.setName(serviceName);
int i = 0;
for (IType type : argumentTypes) {
final Variable parameter = AcceleoPackage.eINSTANCE.getAcceleoFactory().createVariable();
parameter.setName("parameter" + i++);
parameter.setType(parseWhileAqlTypeLiteral(getAqlTypeString(type)));
template.getParameters().add(parameter);
}
Block body = AcceleoPackage.eINSTANCE.getAcceleoFactory().createBlock();
template.setBody(body);
final int offset = module.getAst().getEndPosition(module);
final int line = module.getAst().getEndLine(module);
final int column = module.getAst().getEndColumn(module);
final String replacement;
if (column != 0) {
replacement = newLine + newLine + new AcceleoAstSerializer(newLine).serialize(template);
} else {
replacement = newLine + new AcceleoAstSerializer(newLine).serialize(template);
}
final IAstTextReplacement res = new AstTextReplacement(sourceURI, replacement, offset, line, column,
offset, line, column);
return res;
}
private IAstTextReplacement getServiceReplacement(URI sourceURI, Class<?> cls, String classContent,
String serviceName, IType returnType, List<IType> argumentTypes) {
final StringBuilder replacement = new StringBuilder();
replacement.append("\tpublic ");
try {
if (cls.getConstructors().length == 0) {
replacement.append("static ");
}
} catch (SecurityException e) {
// nothing to do here
}
replacement.append(getJavaStringType(returnType));
replacement.append(" ");
replacement.append(serviceName);
replacement.append("(");
final StringJoiner joiner = new StringJoiner(AcceleoParser.COMMA + SPACE);
int i = 0;
for (IType type : argumentTypes) {
joiner.add(getJavaStringType(type) + " parameter" + i++);
}
replacement.append(joiner.toString());
replacement.append(") {" + newLine);
replacement.append("\t\treturn null;" + newLine);
replacement.append("\t}" + newLine);
final int[][] classLinesAndColumns = AQLUtils.getLinesAndColumns(classContent);
final int offset = classContent.lastIndexOf("}") - 1;
final int line = classLinesAndColumns[offset][0];
final int column = classLinesAndColumns[offset][1];
final IAstTextReplacement res = new AstTextReplacement(sourceURI, replacement.toString(), offset,
line, column, offset, line, column);
return res;
}
/**
* Gets the Java {@link String} representation of the given {@link IType}.
*
* @param type
* @return the Java {@link String} representation of the given {@link IType}
*/
private String getJavaStringType(IType type) {
final String res;
if (type instanceof ICollectionType) {
res = ((ICollectionType)type).getType().getName() + "<" + getJavaStringType(
((ICollectionType)type).getCollectionType()) + ">";
} else if (type instanceof ClassType) {
res = ((ClassType)type).getType().getSimpleName();
} else if (type instanceof EClassifierType) {
final EClassifier eClassifier = ((EClassifierType)type).getType();
if (eClassifier.getInstanceClass() != null) {
res = eClassifier.getInstanceClass().getSimpleName();
} else {
res = eClassifier.getName();
}
} else {
throw new IllegalStateException("unknown type.");
}
return res;
}
private boolean isQueryModule(String qualifiedName) {
return qualifiedName.contains(AcceleoParser.QUALIFIER_SEPARATOR + "requests"
+ AcceleoParser.QUALIFIER_SEPARATOR);
}
private String getSignature(String serviceName, List<IType> argumentTypes) {
final StringBuilder res = new StringBuilder();
res.append(serviceName);
res.append(AcceleoParser.OPEN_PARENTHESIS);
final StringJoiner joiner = new StringJoiner(AcceleoParser.COMMA + SPACE);
for (IType argumentType : argumentTypes) {
joiner.add(argumentType.toString());
}
res.append(joiner.toString());
res.append(AcceleoParser.CLOSE_PARENTHESIS);
return res.toString();
}
/**
* Parses while matching an AQL expression.
*
* @param expression
* the expression to parse
* @return the corresponding {@link AstResult}
*/
protected AstResult parseWhileAqlExpression(String expression) {
return AQLUtils.parseWhileAqlExpression(expression).getAstResult();
}
/**
* Parses while matching an AQL expression.
*
* @param expression
* the expression to parse
* @return the corresponding {@link AstResult}
*/
protected AstResult parseWhileAqlTypeLiteral(String expression) {
return AQLUtils.parseWhileAqlTypeLiteral(expression);
}
/**
* Gets the AQL {@link String} representation of the given {@link IType}.
*
* @param type
* the {@link IType}
* @return the AQL {@link String} representation of the given {@link IType}
*/
protected String getAqlTypeString(IType type) {
return AQLUtils.getAqlTypeString(type);
}
}