|
| 1 | +const vscode = require("vscode"); |
| 2 | + |
| 3 | +const decorationType = vscode.window.createTextEditorDecorationType({ |
| 4 | + backgroundColor: 'rgba(255, 0, 0, 0.3)' |
| 5 | +}); |
| 6 | +function extractImports(importStatement) { |
| 7 | + const itemsRegex = /import\s*\{(.*?)\}\s*from.*/; |
| 8 | + const fileRegex = /\/([^\/"]+)\.sol\";/; |
| 9 | + |
| 10 | + const itemsMatch = importStatement.match(itemsRegex); |
| 11 | + if (itemsMatch) { |
| 12 | + // This was an import with named items. |
| 13 | + // Split the match into individual items, removing leading/trailing whitespace. |
| 14 | + const items = itemsMatch[1].split(',').map(item => item.trim()); |
| 15 | + return items; |
| 16 | + } else { |
| 17 | + // This was an import with a file. |
| 18 | + const fileMatch = importStatement.match(fileRegex); |
| 19 | + if (fileMatch) { |
| 20 | + // Extract the contract/file name from the path. |
| 21 | + const filePathParts = fileMatch[1].split('/'); |
| 22 | + const fileNameParts = filePathParts[filePathParts.length - 1].split('.'); |
| 23 | + const contractName = fileNameParts[0]; |
| 24 | + return [contractName]; |
| 25 | + } else { |
| 26 | + // This import statement didn't match either format. |
| 27 | + return []; |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +// Highlight unused imports for the active Solidity editor when the extension is activated |
| 33 | +async function unusedImportsActiveFile(editor) { |
| 34 | + if (editor && editor.document.languageId == "solidity") { |
| 35 | + editor.setDecorations(decorationType, []); |
| 36 | + |
| 37 | + const text = editor.document.getText(); |
| 38 | + const importRegex = /import\s+((?:\{.+?\}\s+from\s+)?(?:\".*?\"|'.*?'));/g; |
| 39 | + const imports = text.match(importRegex) || []; |
| 40 | + const unusedImportDecorations = []; |
| 41 | + |
| 42 | + for (const importStatement of imports) { |
| 43 | + const imports = extractImports(importStatement); |
| 44 | + for (const item of imports) { |
| 45 | + const filePath = item; |
| 46 | + const regex = new RegExp(item, 'g'); |
| 47 | + const itemOccurancesInImportStatement = (importStatement.replace(/\.sol\b/g, '').match(regex) || []).length; |
| 48 | + const totalOccurrencesOfItem = (text.match(new RegExp(filePath, 'g')) || []).length; |
| 49 | + if (totalOccurrencesOfItem == itemOccurancesInImportStatement) { |
| 50 | + const lineIndex = editor.document.getText().split('\n').findIndex(line => line.includes(importStatement)); |
| 51 | + const range = new vscode.Range(editor.document.lineAt(lineIndex).range.start, editor.document.lineAt(lineIndex).range.end); |
| 52 | + |
| 53 | + unusedImportDecorations.push({ range, ...{ hoverMessage: "Unused import" } }); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + editor.setDecorations(decorationType, unusedImportDecorations); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | +module.exports = { unusedImportsActiveFile }; |
0 commit comments