-
-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathModuleInstantiation.ts
More file actions
226 lines (206 loc) · 6.77 KB
/
ModuleInstantiation.ts
File metadata and controls
226 lines (206 loc) · 6.77 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
// SPDX-License-Identifier: MIT
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import { Ctags, Symbol } from '../ctags';
import { getExtensionLogger } from '../logging';
const logger = () => getExtensionLogger('Command', 'ModuleInstantiation');
export function instantiateModuleInteract() {
if (!isCtagsEnabled()) {
vscode.window.showInformationMessage(
'Verilog-HDL/SystemVerilog: Ctags integration is disabled (verilog.ctags.enabled).'
);
return;
}
if (!vscode.window.activeTextEditor) {
vscode.window.showErrorMessage('No active text editor found');
return;
}
const filePath = path.dirname(vscode.window.activeTextEditor.document.fileName);
selectFile(filePath).then((srcpath) => {
if (srcpath === undefined) {
return;
}
instantiateModule(srcpath).then((inst) => {
if (inst && vscode.window.activeTextEditor) {
vscode.window.activeTextEditor.insertSnippet(inst);
}
});
});
}
export async function instantiateModule(srcpath: string): Promise<vscode.SnippetString | undefined> {
if (!isCtagsEnabled()) {
return undefined;
}
// Using Ctags to get all the modules in the file
let moduleName: string = '';
let portsName: string[] = [];
let parametersName: string[] = [];
if (!vscode.window.activeTextEditor) {
return undefined;
}
const file: vscode.TextDocument = vscode.window.activeTextEditor.document;
const log = logger();
const ctags: ModuleTags = new ModuleTags(log, file);
log.info`Executing ctags for module instantiation`;
const output = await ctags.execCtags(srcpath);
await ctags.buildSymbolsList(output);
let module: Symbol | undefined;
const modules: Symbol[] = ctags.symbols.filter((tag) => tag.type === 'module');
// No modules found
if (modules.length <= 0) {
vscode.window.showErrorMessage('Verilog-HDL/SystemVerilog: No modules found in the file');
return undefined;
}
// Only one module found
else if (modules.length === 1) {
module = modules[0];
}
// many modules found
else if (modules.length > 1) {
const selectedModuleName = await vscode.window.showQuickPick(
ctags.symbols.filter((tag) => tag.type === 'module').map((tag) => tag.name),
{
placeHolder: 'Choose a module to instantiate',
}
);
if (selectedModuleName === undefined) {
return undefined;
}
moduleName = selectedModuleName;
module = modules.filter((tag) => tag.name === moduleName)[0];
}
if (!module) {
return undefined;
}
const scope = module.parentScope !== '' ? `${module.parentScope }.${ module.name}` : module.name;
const ports: Symbol[] = ctags.symbols.filter(
(tag) => tag.type === 'port' && tag.parentType === 'module' && tag.parentScope === scope
);
portsName = ports.map((tag) => tag.name);
const params: Symbol[] = ctags.symbols.filter(
(tag) =>
tag.type === 'parameter' && tag.parentType === 'module' && tag.parentScope === scope
);
parametersName = params.map((tag) => tag.name);
log.info`Module name: ${module.name}`;
let paramString = ``;
if (parametersName.length > 0) {
paramString = `\n#(\n${instantiatePort(parametersName)})\n`;
}
log.info`portsName: ${portsName.toString()}`;
return new vscode.SnippetString()
.appendText(`${module.name } `)
.appendText(paramString)
.appendPlaceholder('u_')
.appendPlaceholder(`${module.name}(\n`)
.appendText(instantiatePort(portsName))
.appendText(');\n');
}
function isCtagsEnabled(): boolean {
const config = vscode.workspace.getConfiguration('verilog.ctags');
return config.get<boolean>('enabled', false);
}
function getIndentationString(): string {
const editorConfig = vscode.workspace.getConfiguration('editor');
const useSpaces = editorConfig.get<boolean>('insertSpaces', true);
const tabSize = editorConfig.get<number>('tabSize', 4);
if (useSpaces) {
return ' '.repeat(tabSize);
}
return '\t';
}
function instantiatePort(ports: string[]): string {
let port = '';
let maxLen = 0;
const indent = getIndentationString();
for (let i = 0; i < ports.length; i++) {
if (ports[i].length > maxLen) {
maxLen = ports[i].length;
}
}
// .NAME(NAME)
for (let i = 0; i < ports.length; i++) {
let element = ports[i];
const padding = maxLen - element.length + 1;
element = element + ' '.repeat(padding);
port += indent;
port += `.${element}(${element})`;
if (i !== ports.length - 1) {
port += ',';
}
port += '\n';
}
return port;
}
async function selectFile(currentDir?: string): Promise<string | undefined> {
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
currentDir = currentDir || workspaceRoot;
if (!currentDir) {
return undefined;
}
const dirs = getDirectories(currentDir);
// if is subdirectory, add '../'
if (currentDir !== workspaceRoot) {
dirs.unshift('..');
}
// all files ends with '.sv'
const files = getFiles(currentDir).filter((file) => file.endsWith('.v') || file.endsWith('.sv'));
// available quick pick items
// Indicate folders in the Quick pick
const items: vscode.QuickPickItem[] = [];
dirs.forEach((dir) => {
items.push({
label: dir,
description: 'folder',
});
});
files.forEach((file) => {
items.push({
label: file,
});
});
const selected = await vscode.window
.showQuickPick(items, {
placeHolder: 'Choose the module file',
});
if (!selected) {
return undefined;
}
// if is a directory
const location = path.join(currentDir, selected.label);
if (fs.statSync(location).isDirectory()) {
return selectFile(location);
}
// return file path
return location;
}
function getDirectories(srcpath: string): string[] {
return fs
.readdirSync(srcpath)
.filter((file) => fs.statSync(path.join(srcpath, file)).isDirectory());
}
function getFiles(srcpath: string): string[] {
return fs.readdirSync(srcpath).filter((file) => fs.statSync(path.join(srcpath, file)).isFile());
}
class ModuleTags extends Ctags {
buildSymbolsList(tags: string): Promise<void> {
if (tags === '') {
return Promise.resolve();
}
// Parse ctags output
const lines: string[] = tags.split(/\r?\n/);
lines.forEach((line) => {
if (line !== '') {
const tag: Symbol | undefined = this.parseTagLine(line);
// add only modules, ports and parameters
// Use 'parameter' type instead of 'constant' after #102
if (tag && (tag.type === 'module' || tag.type === 'port' || tag.type === 'parameter')) {
this.symbols.push(tag);
}
}
});
// skip finding end tags
return Promise.resolve();
}
}