This repository has been archived by the owner on Apr 13, 2023. It is now read-only.
/
IdeaCeylonParser.ceylon
487 lines (470 loc) · 22.4 KB
/
IdeaCeylonParser.ceylon
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
/********************************************************************************
* Copyright (c) {date} Red Hat Inc. and/or its affiliates and others
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/
import ceylon.language {
ceylonTrue=true,
ceylonFalse=false
}
import com.intellij.codeInsight.completion {
CompletionInitializationContext
}
import com.intellij.lang {
ASTNode,
Language
}
import com.intellij.psi {
PsiElement,
PsiDocumentManager,
PsiFile
}
import com.intellij.psi.stubs {
PsiFileStub
}
import com.intellij.psi.tree {
IStubFileElementType
}
import org.eclipse.ceylon.ide.common.model.parsing {
sourceCodeParser
}
import org.eclipse.ceylon.ide.common.typechecker {
ExternalPhasedUnit
}
import java.io {
StringReader
}
import java.lang.ref {
WeakReference
}
import java.util {
JList=List
}
import org.antlr.runtime {
RecognitionException,
CommonToken
}
import org.eclipse.ceylon.ide.intellij.util {
CeylonLogger
}
CeylonLogger<IdeaCeylonParser> ideaCeylonParserLogger = CeylonLogger<IdeaCeylonParser>();
"This class avoids calling a custom parser. Instead, we transform the Ceylon AST generated by
the official parser into an ASTNode tree. Comments and whitespaces are not present in the Ceylon AST,
but we can retrieve them by synchronizing our transformation with a lexer."
shared class IdeaCeylonParser(Language language)
extends IStubFileElementType<PsiFileStub<PsiFile>>(language) {
function structurallyDifferent(JList<CommonToken> puTokens,
JList<CommonToken> localTokens) {
if (puTokens.size() != localTokens.size()) {
return ceylonTrue;
}
for (index in puTokens.size()-1..0) {
value one = puTokens.get(index);
value two = localTokens.get(index);
if (one.stopIndex != two.stopIndex
|| one.startIndex != two.startIndex
|| one.type != two.type) {
return ceylonTrue;
}
}
else {
return ceylonFalse;
}
}
shared actual ASTNode? doParseContents(ASTNode chameleon, PsiElement psi) {
assert(is CeylonFile file = psi);
Boolean verbose = false;
value psiManager = PsiDocumentManager.getInstance(file.project);
value document = psiManager.getDocument(file.originalFile);
value isCommitted = if (exists document) then psiManager.isCommitted(document) else false;
value lastCommittedDocument = psiManager.getLastCommittedDocument(file.originalFile);
value virtualFile = file.originalFile.virtualFile;
value localAnalyzer = file.localAnalyzer else null;
try {
value translator = CompilationUnitTranslator(file, verbose);
value parseResult = sourceCodeParser.parseSourceCode(StringReader(file.text));
if (isCommitted, exists virtualFile) {
if (isInSourceArchive(virtualFile)) {
if (isCommitted) {
ExternalPhasedUnit? externalPhasedUnit;
Boolean parseExplicitelyRequested;
if (exists externalPuToParse = virtualFile.getUserData(uneditedExternalPhasedUnitToParse)) {
externalPhasedUnit = externalPuToParse;
parseExplicitelyRequested = ceylonTrue;
} else if(exists externalPuRef = virtualFile.getUserData(uneditedExternalPhasedUnitRef),
exists externalPuRefGet = externalPuRef.get()) {
externalPhasedUnit = externalPuRefGet;
parseExplicitelyRequested = false;
} else {
externalPhasedUnit = null;
parseExplicitelyRequested = false;
}
if (exists externalPu = externalPhasedUnit) {
value puTokens = externalPu.tokens;
value localTokens = parseResult.tokens;
if (structurallyDifferent(puTokens, localTokens)) {
ideaCeylonParserLogger.warn(() => "Tokens of the externalPhasedUnit are not the same as the parsed tokens for file `` file.originalFile.name ``(``file.originalFile.hash``)", 20);
ideaCeylonParserLogger.trace(() => "translator.translateToAstNode(parseResult.compilationUnit (`` parseResult.compilationUnit.hash ``), parseResult.tokens (`` parseResult.tokens.hash ``)) for file `` file.originalFile.name ``(``file.originalFile.hash``)");
return translator.translateToAstNode(parseResult.compilationUnit, parseResult.tokens);
} else {
ideaCeylonParserLogger.trace(() => "translator.translateToAstNode(externalPu.compilationUnit (`` externalPu.compilationUnit.hash ``), externalPu.tokens (`` externalPu.tokens.hash ``)) for file `` file.originalFile.name ``(``file.originalFile.hash``)");
ASTNode root = translator.translateToAstNode(externalPu.compilationUnit, externalPu.tokens);
void cleanUserDataIfNecessary() {
if(parseExplicitelyRequested) {
virtualFile.putUserData(uneditedExternalPhasedUnitToParse, null);
virtualFile.putUserData(uneditedExternalPhasedUnitRef, WeakReference(externalPhasedUnit));
}
}
void postParseAction();
if (exists localAnalyzer) {
assert(exists lastCommittedDocument);
postParseAction = () {
cleanUserDataIfNecessary();
localAnalyzer.translatedExternalSource(lastCommittedDocument, externalPu);
};
} else {
postParseAction = () {
cleanUserDataIfNecessary();
if (exists future = virtualFile.getUserData(uneditedExternalPhasedUnitFuture)) {
if (! future.done) {
try {
future.set(externalPu);
} catch(Throwable t) {
noop();
}
}
virtualFile.putUserData(uneditedExternalPhasedUnitFuture, null);
}
};
}
root.putUserData(parserConstants.postParseAction, postParseAction);
return root;
}
}
} else {
ideaCeylonParserLogger.trace(() => "translator.translateToAstNode(parseResult.compilationUnit (`` parseResult.compilationUnit.hash ``), parseResult.tokens (`` parseResult.tokens.hash ``)) for file `` file.originalFile.name ``(``file.originalFile.hash``)");
return translator.translateToAstNode(parseResult.compilationUnit, parseResult.tokens);
}
} else {
if (! localAnalyzer exists) {
if (isCommitted, exists projectPhasedUnit = retrieveProjectPhasedUnit(file)) {
value puTokens = projectPhasedUnit.tokens;
value localTokens = parseResult.tokens;
if (structurallyDifferent(puTokens, localTokens)) {
ideaCeylonParserLogger.warn(() => "Tokens of the project phasedUnit are not the same as the parsed tokens for file `` file.originalFile.name ``(``file.originalFile.hash``)", 20);
ideaCeylonParserLogger.trace(() => "translator.translateToAstNode(parseResult.compilationUnit (`` parseResult.compilationUnit.hash ``), parseResult.tokens (`` parseResult.tokens.hash ``)) for file `` file.originalFile.name ``(``file.originalFile.hash``)");
return translator.translateToAstNode(parseResult.compilationUnit, parseResult.tokens);
} else {
ideaCeylonParserLogger.trace(() => "translator.translateToAstNode(projectPhasedUnit.compilationUnit (`` projectPhasedUnit.compilationUnit.hash ``), projectPhasedUnit.tokens (`` projectPhasedUnit.tokens.hash ``)) for file `` file.originalFile.name ``(``file.originalFile.hash``)");
return translator.translateToAstNode(projectPhasedUnit.compilationUnit, projectPhasedUnit.tokens);
}
} else {
ideaCeylonParserLogger.trace(() => "translator.translateToAstNode(parseResult.compilationUnit (`` parseResult.compilationUnit.hash ``), parseResult.tokens (`` parseResult.tokens.hash ``)) for file `` file.originalFile.name ``(``file.originalFile.hash``)");
return translator.translateToAstNode(parseResult.compilationUnit, parseResult.tokens);
}
}
}
}
ideaCeylonParserLogger.trace(() => "translator.translateToAstNode(parseResult.compilationUnit (`` parseResult.compilationUnit.hash ``), parseResult.tokens (`` parseResult.tokens.hash ``)) for file `` file.originalFile.name ``(``file.originalFile.hash``)");
ASTNode root = translator.translateToAstNode(parseResult.compilationUnit, parseResult.tokens);
if (exists localAnalyzer) {
if (! CompletionInitializationContext.dummyIdentifierTrimmed in file.text) {
assert(exists lastCommittedDocument);
root.putUserData(parserConstants.postParseAction, void () {
localAnalyzer.parsedProjectSource(
lastCommittedDocument,
parseResult.compilationUnit,
parseResult.tokens);
});
} else {
ideaCeylonParserLogger.debug(() => "Local analyzer not notified of parsing for file `` file.originalFile.name ``(``file.originalFile.hash``) because the text contains '`` CompletionInitializationContext.dummyIdentifierTrimmed ``'");
}
}
return root;
} catch (RecognitionException re) {
re.cause?.printStackTrace();
}
return null;
}
// // For debugging purposes only
// void dump(ASTNode root, String indent) {
// ideaCeylonParserLogger.debug(() =>
// indent
// + root.elementType.string
// + (if (is LeafPsiElement root) then " (`` root.text ``)" else "" ));
//
// for (child in root.getChildren(null)) {
// dump(child, indent + " ");
// }
// }
//
// class CompilationUnitTranslator(CeylonFile file, Boolean verbose) extends Visitor() {
//
// variable CompositeElement? parent = null;
// late variable Queue<CommonToken> customizedTokens;
// variable Integer index = 0;
//
// shared ASTNode translateToAstNode(Tree.CompilationUnit cu, JList<CommonToken> originalTokens) {
// customizedTokens = LinkedList<CommonToken>();
// value lastToken = Ref<CommonToken>();
//
// for (CommonToken? token in originalTokens) {
// if (exists token) {
// variable value lastStopIndex = -1;
// if (!lastToken.null) {
// lastStopIndex = lastToken.get().stopIndex;
// }
// if (token.type != CeylonLexer.eof
// && lastStopIndex != token.startIndex - 1) {
// value badToken = CommonToken(token.inputStream, -2, 0,
// lastStopIndex + 1,
// token.startIndex - 1);
// customizedTokens.add(badToken);
// }
// customizedTokens.add(token);
// lastToken.set(token);
// }
// }
//
// if (lastToken.get().stopIndex < file.textLength) {
// value badToken = CommonToken(lastToken.get().inputStream, -2, 0,
// lastToken.get().stopIndex + 1,
// file.textLength - 1);
// customizedTokens.add(badToken);
// }
//
// visit(cu);
//
// assert(exists root = parent);
// if (verbose) {
// dump(root, "");
// }
// return root;
// }
//
// shared actual void visit(Tree.CompilationUnit that) {
// super.visit(that);
//
// assert(exists parent = this.parent);
//
// while (!customizedTokens.empty) {
// Token token = customizedTokens.remove();
//
// if (token.type != CeylonLexer.eof) {
// parent.rawAddChildrenWithoutNotifications(buildLeaf(null, getElementType(token.type), token));
// }
//
// if (verbose && ! token.type in parserConstants._NODES_ALLOWED_AT_EOF) {
// ideaCeylonParserLogger.error(()=>"Unexpected token `` token `` in `` file.name ``", 20);
// }
// }
//
// value parentTextLengthRef = Ref<Integer>();
// value fileTextLengthRef = Ref<Integer>();
// ApplicationManager.application.runReadAction(JavaRunnable(() {
// parentTextLengthRef.set(parent.textLength);
// fileTextLengthRef.set(file.textLength);
// }));
// assert(exists parentTextLength = parentTextLengthRef.get());
// assert(exists fileTextLength = fileTextLengthRef.get());
// if (parentTextLength < fileTextLength) {
// String notParsed = file.text.substring(parentTextLength);
// parent.rawAddChildrenWithoutNotifications(LeafPsiElement(TokenType.badCharacter, nativeString(notParsed)));
// }
// }
//
// shared actual void visitAny(Node that) {
// IElementType? type = NodeToIElementTypeMap.get(that);
//
// if (! exists type) {
// ideaCeylonParserLogger.error(()=>"Unknown IElementType for `` that `` in `` that.unit?.fullPath else "unknown" ``", 20);
// return;
// }
//
// variable Boolean parentForced = false;
//
// if (! parent exists) {
// parentForced = languageTrue;
// parent = CompositeElement(type);
// }
//
// if (is Tree.DocLink that) {
// return;
// }
//
// index = consumeTokens(that, index, languageTrue);
//
// Token? token = that.mainToken;
//
// value visitor = OrderedChildrenVisitor();
// try {
// that.visitChildren(visitor);
// } catch (e) {
// that.handleException(e, visitor);
// }
//
// if (exists theToken = that.token,
// visitor.children.empty) {
//
// assert(exists parent = this.parent);
//
// Token peek = customizedTokens.peek();
// if (getTokenLength(peek) == that.endIndex.intValue() - that.startIndex.intValue()) {
// Token toRemove = customizedTokens.remove();
// parent.rawAddChildrenWithoutNotifications(buildLeaf(that, type, toRemove));
// if (verbose) {
// ideaCeylonParserLogger.debug(()=>"t \"" + toRemove.text + "\"");
// }
// index += getTokenLength(toRemove);
// } else {
// CompositeElement comp = CompositeElement(type);
//
// assert(exists token);
// while (index < that.endIndex.intValue()) {
// Token toRemove = customizedTokens.remove();
// comp.rawAddChildrenWithoutNotifications(buildLeaf(null, getElementType(token.type), toRemove));
// if (verbose) {
// ideaCeylonParserLogger.debug(()=>"t \"" + toRemove.text + "\"");
// }
// index += getTokenLength(toRemove);
// }
//
// parent.rawAddChildrenWithoutNotifications(comp);
// }
//
// // TODO should be == but sometimes the tree includes a node that was already included before
// // (see `exists` constructs for example)
// assert (index >= that.endIndex.intValue());
// } else {
// assert(exists oldParent = parent);
// if (!parentForced) {
// parent = CompositeElement(type);
// oldParent.rawAddChildrenWithoutNotifications(parent);
// }
// assert(exists parent=this.parent);
// parent.putUserData(parserConstants._CEYLON_NODE_KEY, that);
//
// for (child in visitor.children) {
// visitAny(child);
// }
//
// index = consumeTokens(that, index, false);
//
// this.parent = oldParent;
// }
// }
//
// IElementType getElementType(Integer idx) {
// if (idx == -2) {
// return TokenType.badCharacter;
// }
// return TokenTypes.fromInt(idx);
// }
//
// TreeElement buildLeaf(Node? ceylonNode, IElementType type, Token token) {
// variable value tokenText = token.text;
// if (tokenText.size != getTokenLength(token)) {
// value tokenType = token.type;
// if (tokenType == CeylonLexer.\iPIDENTIFIER ||
// tokenType == CeylonLexer.\iAIDENTIFIER ||
// tokenType == CeylonLexer.\iLIDENTIFIER) {
// tokenText = "\\i" + tokenText;
// } else if (tokenType == CeylonLexer.\iUIDENTIFIER) {
// tokenText = "\\I" + tokenText;
// } else {
// throw UnsupportedOperationException("Unsupported token type `` token ``");
// }
// }
// if (type in parserConstants._LEAVES_TO_WRAP) {
// value comp = CompositeElement(type);
// value leaf = LeafPsiElement(TokenTypes.fromInt(token.type), nativeString(tokenText));
// comp.rawAddChildrenWithoutNotifications(leaf);
// comp.putUserData(parserConstants._CEYLON_NODE_KEY, ceylonNode);
// return comp;
// } else if (type == TokenType.\iWHITE_SPACE || token.type == CeylonLexer.\iWS) {
// return PsiWhiteSpaceImpl(nativeString(tokenText));
// } else {
// return LeafPsiElement(getElementType(token.type), nativeString(tokenText));
// }
// }
//
// Integer consumeTokens(Node that, variable Integer index, Boolean before) {
// Integer? targetIndex = if (before) then that.startIndex?.intValue() else that.endIndex?.intValue();
//
// if (! exists targetIndex) {
// return index;
// }
//
// if (index > targetIndex) {
// if (verbose) {
// ideaCeylonParserLogger.warn(()=>"WARN : index (``index``) > targetIndex (``targetIndex``)", 20);
// }
// return index;
// }
//
// while (index < targetIndex) {
// Token token = customizedTokens.remove();
// String text = token.text;
// assert(exists parent = this.parent);
// if (token.type == CeylonLexer.\iLINE_COMMENT && text.endsWith("\n")) {
// parent.rawAddChildrenWithoutNotifications(LeafPsiElement(getElementType(token.type),
// nativeString(text.substring(0, text.size-1))));
// parent.rawAddChildrenWithoutNotifications(PsiWhiteSpaceImpl(nativeString("\n")));
// }
// else {
// parent.rawAddChildrenWithoutNotifications(buildLeaf(null, getElementType(token.type), token));
// }
// index += getTokenLength(token);
// if (verbose) {
// ideaCeylonParserLogger.debug(()=>"c \"`` text ``\"");
// }
// }
//
// assert (index == targetIndex);
//
// return index;
// }
//
// Integer getTokenLength(Token token) {
// if (is CommonToken commonToken = token) {
// return commonToken.stopIndex - commonToken.startIndex + 1;
// } else {
// return token.text.size;
// }
// }
// }
//
// class OrderedChildrenVisitor() extends Visitor() {
// value children_ = ArrayList<Node>();
//
// shared actual void visitAny(Node that) {
// children_.add(that);
// }
//
// shared JList<Node> children {
// Collections.sort(children_, object satisfies Comparator<Node> {
// shared actual Integer compare(Node o1, Node o2) {
// JInteger? idx1 = o1.startIndex;
// JInteger? idx2 = o2.startIndex;
//
// if (! exists idx1) {
// return if (! idx2 exists) then 0 else 1;
// }
// if (! exists idx2) {
// return -1;
// }
//
// return idx1.compareTo(idx2);
// }
//
// shared actual Boolean equals(Object that) => (super of Identifiable).equals(that);
// });
//
// return children_;
// }
// }
}