-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpropertyReadWriteCodelens.js
More file actions
491 lines (404 loc) · 15 KB
/
propertyReadWriteCodelens.js
File metadata and controls
491 lines (404 loc) · 15 KB
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
const vscode = require("vscode");
// OutputChannel pour le debug
const outputChannel = vscode.window.createOutputChannel("Property Read Write CodeLens");
class PropertyReadWriteCodeLensProvider {
constructor() {
this.onDidChangeEmitter = new vscode.EventEmitter();
// Cache pour les documents ouverts lors d'une session CodeLens
this.documentCache = new Map();
}
// Récupère les emojis et affixes personnalisés depuis la configuration utilisateur
getConfig() {
const config = vscode.workspace.getConfiguration('propertyReadWriteCodelens');
const readEmoji = config.get('readEmoji', '📖');
const writeEmoji = config.get('writeEmoji', '✏️');
const readAffix = config.get('readAffix', 'reads');
const writeAffix = config.get('writeAffix', 'writes');
const showReads = config.get('showReads', true);
const showWrites = config.get('showWrites', true);
return { readEmoji, writeEmoji, readAffix, writeAffix, showReads, showWrites };
}
get onDidChangeCodeLenses() {
return this.onDidChangeEmitter.event;
}
refresh() {
this.onDidChangeEmitter.fire();
}
// Utilise l'API Document Symbols de VS Code pour une analyse précise
async provideCodeLenses(doc, token) {
const lenses = [];
this.documentCache.clear();
this.documentCache.set(doc.uri.toString(), doc);
if (token.isCancellationRequested) {
return lenses;
}
try {
const symbols = await vscode.commands.executeCommand(
'vscode.executeDocumentSymbolProvider',
doc.uri
);
if (symbols && Array.isArray(symbols)) {
for (const symbol of symbols) {
if (token.isCancellationRequested) {
return lenses;
}
if (symbol.kind === vscode.SymbolKind.Class) {
await this.processClassSymbol(symbol, doc, lenses, token);
} else if (symbol.kind === vscode.SymbolKind.Variable ||
symbol.kind === vscode.SymbolKind.Constant) {
await this.processVariableSymbol(symbol, doc, lenses, token);
}
}
}
} catch (error) {
outputChannel.appendLine('[CodeLens] Erreur lors de l\'analyse des symboles: ' + error?.message);
outputChannel.appendLine(error?.stack || String(error));
}
return lenses;
}
// Traite les variables/constantes qui peuvent contenir des objets avec propriétés
async processVariableSymbol(variableSymbol, doc, lenses, token) {
if (variableSymbol.children && Array.isArray(variableSymbol.children)) {
for (const child of variableSymbol.children) {
// Vérifie l'annulation
if (token.isCancellationRequested) {
return;
}
// Si c'est une propriété directe
if (child.kind === vscode.SymbolKind.Property || child.kind === vscode.SymbolKind.Field) {
await this.processPropertySymbol(child, doc, lenses, token);
}
// Si c'est une classe (ex: classe anonyme instanciée)
else if (child.kind === vscode.SymbolKind.Class) {
// Appel récursif pour traiter toutes les propriétés internes de la classe
await this.processClassSymbol(child, doc, lenses, token);
}
}
} else {
}
}
// Traite les symboles de classe pour trouver les propriétés
async processClassSymbol(classSymbol, doc, lenses, token) {
if (classSymbol.children && Array.isArray(classSymbol.children)) {
for (const child of classSymbol.children) {
// Vérifie l'annulation
if (token.isCancellationRequested) {
return;
}
// Recherche les propriétés de classe déclarées explicitement
if (child.kind === vscode.SymbolKind.Property ||
child.kind === vscode.SymbolKind.Field) {
await this.processPropertySymbol(child, doc, lenses, token);
}
// Traite les constructeurs pour trouver les propriétés this.property
else if (child.kind === vscode.SymbolKind.Constructor) {
await this.processConstructorForProperties(child, classSymbol, doc, lenses, token);
}
}
} else {
}
}
// Traite le constructeur pour trouver les propriétés this.property
async processConstructorForProperties(constructorSymbol, classSymbol, doc, lenses, token) {
try {
// Récupère le contenu du constructeur
const constructorRange = constructorSymbol.range;
const constructorText = doc.getText(constructorRange);
// Regex pour trouver les affectations this.property =
const thisPropertyRegex = /this\.(\w+)\s*=/g;
const properties = new Set();
let match;
while ((match = thisPropertyRegex.exec(constructorText)) !== null) {
properties.add(match[1]);
}
// Pour chaque propriété trouvée, cherche sa position et crée un CodeLens
for (const propName of properties) {
if (token.isCancellationRequested) {
return;
}
await this.processThisProperty(propName, classSymbol, doc, lenses, token);
}
} catch (error) {
outputChannel.appendLine(`[CodeLens] Erreur lors de l'analyse du constructeur: ${error?.message}`);
outputChannel.appendLine(error?.stack || String(error));
}
}
// Traite une propriété this.property trouvée dans le constructeur
async processThisProperty(propName, classSymbol, doc, lenses, token) {
try {
// Trouve la première occurrence de this.propName dans la classe
const classRange = classSymbol.range;
const classText = doc.getText(classRange);
const propPattern = new RegExp(`this\\.${propName}\\s*=`, 'g');
const match = propPattern.exec(classText);
if (match) {
// Calcule la position absolue dans le document
const classStartOffset = doc.offsetAt(classRange.start);
const propOffset = classStartOffset + match.index;
const propPosition = doc.positionAt(propOffset);
// Crée un range pour la propriété
const propRange = new vscode.Range(
propPosition,
new vscode.Position(propPosition.line, propPosition.character + `this.${propName}`.length)
);
// Utilise la méthode existante pour traiter la propriété
await this.processPropertySymbolByName(propName, propRange, doc, lenses, token);
}
} catch (error) {
outputChannel.appendLine(`[CodeLens] Erreur lors du traitement de this.${propName}: ${error?.message}`);
outputChannel.appendLine(error?.stack || String(error));
}
}
// Version modifiée pour traiter une propriété par nom et range
async processPropertySymbolByName(propName, range, doc, lenses, token) {
try {
// Utilise executeReferenceProvider pour trouver toutes les références
const refs = await vscode.commands.executeCommand(
"vscode.executeReferenceProvider",
doc.uri,
range.start
);
// Vérifie l'annulation après l'appel async
if (token.isCancellationRequested) {
return;
}
let reads = 0, writes = 0;
const readRefs = [], writeRefs = [];
if (refs && Array.isArray(refs)) {
for (const ref of refs) {
// Ignore la déclaration elle-même
if (this.isDeclaration(ref, range, doc.uri)) {
continue;
}
try {
const refDoc = await this.getDocument(ref.uri);
if (!refDoc) continue;
if (this.isWriteReference(ref, refDoc, propName)) {
writes++;
writeRefs.push(ref);
} else {
reads++;
readRefs.push(ref);
}
} catch (error) {
console.warn(`[CodeLens] Erreur lors du traitement de la référence:`, error);
continue;
}
}
}
// Utilise les emojis et affixes personnalisés
const { readEmoji, writeEmoji, readAffix, writeAffix, showReads, showWrites } = this.getConfig();
// Ajoute les CodeLens
if (reads > 0 && showReads) {
lenses.push(new vscode.CodeLens(range, {
title: `${readEmoji} ${reads} ${readAffix}`,
command: "propertyReadWriteCodelens.showReads",
arguments: [doc.uri, range.start, "reads", readRefs],
}));
}
if (writes > 0 && showWrites) {
lenses.push(new vscode.CodeLens(range, {
title: `${writeEmoji} ${writes} ${writeAffix}`,
command: "propertyReadWriteCodelens.showWrites",
arguments: [doc.uri, range.start, "writes", writeRefs],
}));
}
} catch (error) {
outputChannel.appendLine(`[CodeLens] Erreur lors du traitement de ${propName}: ${error?.message}`);
outputChannel.appendLine(error?.stack || String(error));
}
}
// Traite une propriété spécifique
async processPropertySymbol(propertySymbol, doc, lenses, token) {
const propName = propertySymbol.name;
const range = propertySymbol.range || propertySymbol.location?.range;
if (!range) {
console.warn(`[CodeLens] Pas de range pour la propriété ${propName}`);
return;
}
try {
// Utilise executeReferenceProvider pour trouver toutes les références
const refs = await vscode.commands.executeCommand(
"vscode.executeReferenceProvider",
doc.uri,
range.start
);
// Vérifie l'annulation après l'appel async
if (token.isCancellationRequested) {
return;
}
let reads = 0, writes = 0;
const readRefs = [], writeRefs = [];
if (refs && Array.isArray(refs)) {
for (const ref of refs) {
// Ignore la déclaration elle-même
if (this.isDeclaration(ref, range, doc.uri)) {
continue;
}
try {
const refDoc = await this.getDocument(ref.uri);
if (!refDoc) continue;
if (this.isWriteReference(ref, refDoc, propName)) {
writes++;
writeRefs.push(ref);
} else {
reads++;
readRefs.push(ref);
}
} catch (error) {
console.warn(`[CodeLens] Erreur lors du traitement de la référence:`, error);
continue;
}
}
}
// Utilise les emojis et affixes personnalisés
const { readEmoji, writeEmoji, readAffix, writeAffix, showReads, showWrites } = this.getConfig();
// Ajoute les CodeLens
if (reads > 0 && showReads) {
lenses.push(new vscode.CodeLens(range, {
title: `${readEmoji} ${reads} ${readAffix}`,
command: "propertyReadWriteCodelens.showReads",
arguments: [doc.uri, range.start, "reads", readRefs],
}));
}
if (writes > 0 && showWrites) {
lenses.push(new vscode.CodeLens(range, {
title: `${writeEmoji} ${writes} ${writeAffix}`,
command: "propertyReadWriteCodelens.showWrites",
arguments: [doc.uri, range.start, "writes", writeRefs],
}));
}
} catch (error) {
outputChannel.appendLine(`[CodeLens] Erreur lors du traitement de ${propName}: ${error?.message}`);
outputChannel.appendLine(error?.stack || String(error));
}
}
// Vérifie si une référence est la déclaration elle-même
isDeclaration(ref, propertyRange, docUri) {
return ref.range.start.line === propertyRange.start.line &&
ref.range.start.character === propertyRange.start.character &&
ref.uri.toString() === docUri.toString();
}
// Vérifie si une référence est une écriture
isWriteReference(ref, refDoc, propName) {
if (ref.range.start.line < 0 || ref.range.start.line >= refDoc.lineCount) {
return false;
}
const refLine = refDoc.lineAt(ref.range.start.line).text;
const refPosition = ref.range.start.character;
if (refPosition < 0 || refPosition >= refLine.length) {
return false;
}
const afterProp = refLine.substring(refPosition + propName.length).trim();
const beforeProp = refLine.substring(0, refPosition).trim();
// Patterns d'écriture
return afterProp.match(/^(\s*=(?!=)|(\+\+|--|\+=|-=|\*=|\/=|%=))/) ||
beforeProp.match(/(\+\+|--)\s*$/) ||
refLine.includes(`${propName} =`);
}
// Méthode optimisée pour récupérer les documents avec cache
async getDocument(uri) {
const uriString = uri.toString();
// Vérifie d'abord le cache
if (this.documentCache.has(uriString)) {
return this.documentCache.get(uriString);
}
// Vérifie si le document est déjà ouvert dans l'éditeur (plus rapide)
const openDoc = vscode.workspace.textDocuments.find(
(doc) => doc.uri.toString() === uriString
);
if (openDoc) {
this.documentCache.set(uriString, openDoc);
return openDoc;
}
// Sinon, ouvre le document (plus lent)
try {
const doc = await vscode.workspace.openTextDocument(uri);
this.documentCache.set(uriString, doc);
return doc;
} catch (error) {
outputChannel.appendLine(`[CodeLens] Impossible d'ouvrir le document ${uriString}: ${error?.message}`);
outputChannel.appendLine(error?.stack || String(error));
return null;
}
}
}
function activate(context) {
outputChannel.appendLine('[CodeLens] Extension Property Read Write CodeLens activée !');
const provider = new PropertyReadWriteCodeLensProvider();
const codeLensDisposable = vscode.languages.registerCodeLensProvider(
[
{ language: "javascript", scheme: "file" },
{ language: "typescript", scheme: "file" },
],
provider
);
// Rafraîchir les CodeLens si la configuration change (emoji)
const configDisposable = vscode.workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('propertyReadWriteCodelens.readEmoji') || e.affectsConfiguration('propertyReadWriteCodelens.writeEmoji')) {
provider.refresh();
}
});
context.subscriptions.push(
codeLensDisposable,
configDisposable,
vscode.commands.registerCommand("propertyReadWriteCodelens.refresh", () =>
provider.refresh()
),
// Commande pour afficher uniquement les lectures
vscode.commands.registerCommand(
"propertyReadWriteCodelens.showReads",
async (uri, position, type, references) => {
try {
if (
references &&
Array.isArray(references) &&
references.length > 0
) {
await vscode.commands.executeCommand(
"editor.action.peekLocations",
uri,
position,
references,
"peek"
);
}
} catch (error) {
outputChannel.appendLine("Erreur lors de l'affichage des lectures: " + error?.message);
outputChannel.appendLine(error?.stack || String(error));
vscode.window.showErrorMessage(
"Impossible d'afficher les références de lecture"
);
}
}
),
// Commande pour afficher uniquement les écritures
vscode.commands.registerCommand(
"propertyReadWriteCodelens.showWrites",
async (uri, position, type, references) => {
try {
if (
references &&
Array.isArray(references) &&
references.length > 0
) {
await vscode.commands.executeCommand(
"editor.action.peekLocations",
uri,
position,
references,
"peek"
);
}
} catch (error) {
outputChannel.appendLine("Erreur lors de l'affichage des écritures: " + error?.message);
outputChannel.appendLine(error?.stack || String(error));
vscode.window.showErrorMessage(
"Impossible d'afficher les références d'écriture"
);
}
}
)
);
}
module.exports = { activate };