forked from damien122/Autoit-Visual-Studio-Extension
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathutil.js
354 lines (305 loc) · 11.1 KB
/
util.js
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
const fs = require('fs');
const path = require('path');
const { CompletionItemKind, MarkdownString, workspace } = require('vscode');
const { findFilepath } = require('./ai_config').default;
const descriptionHeader = '|Description |Value |\n|:---|:---:|\n';
const valueFirstHeader = '\n| | | \n|---:|:---:|:---|';
const trueFalseHeader = `\n| | |
:---|:---:|:---`;
const opt = '**[optional]**';
const br = '\u0020\u0020';
const defaultZero = `${br + br}\`Default = 0\``;
// eslint-disable-next-line no-extend-native
RegExp.prototype.setFlags = function setFlags(flags) {
return RegExp(this.source, flags);
};
const setDetailAndDocumentation = (array, detail, doc) => {
const newArray = array.map(item => {
return { ...item, detail, documentation: `${item.documentation}\n\n*${doc}*` };
});
return newArray;
};
const AI_CONSTANTS = [
'$MB_ICONERROR',
'$MB_ICONINFORMATION',
'$MB_YESNO',
'$MB_TASKMODAL',
'$IDYES',
'$IDNO',
];
const AUTOIT_MODE = { language: 'autoit', scheme: 'file' };
const isSkippableLine = line => {
if (line.isEmptyOrWhitespace) {
return true;
}
const firstChar = line.text.charAt(line.firstNonWhitespaceCharacterIndex);
if (firstChar === ';') {
return true;
}
if (firstChar === '#') {
if (/^\s*#(cs|ce|comments-start|comments-end)/.test(line.text)) {
return false;
}
return true;
}
return false;
};
const getIncludeText = filePath => {
return fs.readFileSync(filePath).toString();
};
/**
* Returns the include path of a given file or path based on the provided document.
* @param {string} fileOrPath - The file or path to get the include path of.
* @param {TextDocument} document - The document object to use for determining the include path.
* @returns {string} The include path of the given file or path.
*/
const getIncludePath = (fileOrPath, document) => {
let includePath = '';
if (fileOrPath.startsWith(':', 1)) {
includePath = fileOrPath;
} else {
const docDir = path.dirname(document.fileName);
includePath = path.join(docDir, fileOrPath);
}
includePath = includePath.charAt(0).toUpperCase() + includePath.slice(1);
return includePath;
};
let parenTriggerOn = workspace.getConfiguration('autoit').get('enableParenTriggerForFunctions');
workspace.onDidChangeConfiguration(event => {
if (event.affectsConfiguration('autoit.enableParenTriggerForFunctions'))
parenTriggerOn = workspace.getConfiguration('autoit').get('enableParenTriggerForFunctions');
});
/**
* Generates a new array of Completions that include a common kind, detail and
* potentially commitCharacter(s)
* @param {*} entries The array of Completions to be modified
* @param {*} kind The enum value of CompletionItemKind to determine icon
* @param {*} detail Additional information about the entries
* @param {*} requiredScript Script where completion is defined
* @returns Returns an array of Completion objects
*/
const fillCompletions = (entries, kind, detail = '', requiredScript = '') => {
const filledCompletion = entries.map(entry => {
const newDoc = new MarkdownString(entry.documentation);
if (requiredScript) newDoc.appendCodeblock(`#include <${requiredScript}>`, 'autoit');
const newDetail = entry.detail ? entry.detail + detail : detail;
return {
...entry,
kind,
detail: newDetail,
get commitCharacters() {
return kind === CompletionItemKind.Function && parenTriggerOn ? ['('] : [];
},
documentation: newDoc,
};
});
return filledCompletion;
};
/**
* Generates an object of Hover objects for a set of signatures
* @param signatures An object containing Signature objects
* @returns Returns an empty object or with Hover objects
*/
const signatureToHover = signatures => {
const hoverObjects = {};
for (const item of Object.keys(signatures)) {
hoverObjects[item] = [
signatures[item].documentation,
`\`\`\`\r${signatures[item].label}\r\`\`\``,
];
}
return hoverObjects;
};
/**
* Generates an object of Hover objects from completions
* @param completions An object containing Completions
* @returns Returns an empty object or Hover objects
*/
const completionToHover = completions => {
const hoverObjects = {};
completions.forEach(item => {
hoverObjects[item.label] = item.documentation;
});
return hoverObjects;
};
const includePattern = /^#include\s"(.+)"/gm;
const functionPattern = /^[\t ]*(?:volatile[\t ]+)?Func[\t ]+(\w+)[\t ]*\(/i;
const functionDefinitionRegex = /^[\t ]*(?:volatile[\t ]+)?Func[\t ]+((\w+)[\t ]*\((.*)\))/gim;
const variablePattern = /(?:["'].*?["'])|(?:;.*)|(\$\w+)/g;
const regionPattern = /^[\t ]{0,}#region\s[- ]{0,}(.+)/i;
const libraryIncludePattern = /^#include\s+<([\w.]+\.au3)>/gm;
/**
* Generates an array of Completions from a signature object
* @param signatures Signature object
* @param kind The CompletionItemKind
* @param detail A human-readable string with additional information about this item, like type or symbol information.
* @returns {Array} an array of completions
*/
const signatureToCompletion = (signatures, kind, detail) => {
const completionSet = Object.keys(signatures).map(key => {
return { label: key, documentation: signatures[key].documentation, kind, detail };
});
return completionSet;
};
/**
* Generates an array of Include scripts to search
* that includes the full range of the region's body
* @param {TextDocument} document The current document to search
* @param {String} docText The text from the document
* @param {Array} scriptsToSearch The destination array
* @returns SymbolInformation
*/
const getIncludeScripts = (document, docText, scriptsToSearch) => {
const relativeInclude = /^\s*#include\s"(.+)"/gm;
const libraryInclude = /^\s*#include\s<(.+)>/gm;
let includeFile;
let scriptContent;
let found = relativeInclude.exec(docText);
while (found) {
// Check if file exists in document directory
includeFile = getIncludePath(found[1], document);
if (!fs.existsSync(includeFile)) {
// Find first instance using include paths
includeFile = findFilepath(found[1], false);
}
if (includeFile && scriptsToSearch.indexOf(includeFile) === -1) {
scriptsToSearch.push(includeFile);
scriptContent = getIncludeText(includeFile);
getIncludeScripts(document, scriptContent, scriptsToSearch);
}
found = relativeInclude.exec(docText);
}
found = libraryInclude.exec(docText);
while (found) {
// Find first instance using include paths
includeFile = findFilepath(found[1], false);
if (includeFile && scriptsToSearch.indexOf(includeFile) === -1) {
scriptsToSearch.push(includeFile);
scriptContent = getIncludeText(includeFile);
getIncludeScripts(document, scriptContent, scriptsToSearch);
}
found = libraryInclude.exec(docText);
}
};
/**
* Extracts the documentation for a specific parameter from a given text.
*
* @param {string} text - The text containing the parameter documentation.
* @param {string} paramEntry - The name of the parameter entry to extract the documentation for.
* @param {number} headerIndex - The index where the header starts in the text.
* @returns {string} The documentation for the specified parameter, or an empty string if not found.
*/
const extractParamDocumentation = (text, paramEntry, headerIndex) => {
if (headerIndex === -1) return '';
const headerSubstring = text.substring(headerIndex);
const parameterDocRegex = new RegExp(
`;\\s*(?:Parameters\\s*\\.+:)?\\s*(?:\\${paramEntry})\\s+-\\s(?<documentation>.+)`,
);
const paramDocMatch = parameterDocRegex.exec(headerSubstring);
const paramDoc = paramDocMatch ? paramDocMatch.groups.documentation : '';
return paramDoc;
};
/**
* Returns an object with each parameter as a key and an object with label and documentation properties as its value.
* @param {string} paramText - A string of comma-separated parameters.
* @param {string} text - The text from the document
* @returns {Object} An object with each parameter as a key and an object with label and documentation properties as its value.
*/
const getParams = (paramText, text, headerIndex) => {
const params = {};
if (!paramText) return params;
const paramList = paramText.split(',');
for (const param of paramList) {
const paramEntry = param
.split('=')[0]
.trim()
.replace(/^ByRef\s*/, '');
const paramDoc = extractParamDocumentation(text, paramEntry, headerIndex);
params[paramEntry] = {
label: paramEntry,
documentation: paramDoc,
};
}
return params;
};
const getHeaderRegex = functionName =>
new RegExp(
`;\\s*Name\\s*\\.+:\\s+${functionName}\\s*[\r\n]` +
`;\\s+Description\\s*\\.+:\\s+(?<description>.+)[\r\n]`,
);
/**
* Extracts function data from pattern and returns an object containing function name and object
* @param {RegExpExecArray} functionMatch The results of the includeFuncPattern match
* @param {string} fileText The contents of the AutoIt Script
* @param {string} fileName The name of the AutoIt Script
* @returns {Object} Object containing function name and object
*/
const buildFunctionSignature = (functionMatch, fileText, fileName) => {
const { 1: functionLabel, 2: functionName, 3: paramsText } = functionMatch;
const headerRegex = getHeaderRegex(functionName);
const headerMatch = fileText.match(headerRegex);
const description = headerMatch ? `${headerMatch.groups.description}\r` : '';
const functionDocumentation = `${description}Included from ${fileName}`;
const functionIndex = headerMatch ? headerMatch.index : -1;
return {
functionName,
functionObject: {
label: functionLabel,
documentation: functionDocumentation,
params: getParams(paramsText, fileText, functionIndex),
},
};
};
/**
* Returns an object of AutoIt functions found within a VSCode TextDocument
* @param {string} fileName The name of the AutoIt script
* @param {vscode.TextDocument} doc The TextDocument object representing the AutoIt script
* @returns {Object} Object containing SignatureInformation objects
*/
const getIncludeData = (fileName, doc) => {
const functions = {};
let filePath = getIncludePath(fileName, doc);
if (!fs.existsSync(filePath)) {
// Find first instance using include paths
filePath = findFilepath(fileName, false);
}
let functionMatch = null;
const fileData = getIncludeText(filePath);
do {
functionMatch = functionDefinitionRegex.exec(fileData);
if (functionMatch) {
const functionData = buildFunctionSignature(functionMatch, fileData, fileName);
functions[functionData.functionName] = functionData.functionObject;
}
} while (functionMatch);
return functions;
};
module.exports = {
descriptionHeader,
valueFirstHeader,
setDetail: setDetailAndDocumentation,
opt,
trueFalseHeader,
br,
AI_CONSTANTS,
defaultZero,
AUTOIT_MODE,
isSkippableLine,
getIncludeText,
getIncludePath,
fillCompletions,
signatureToHover,
includePattern,
functionPattern,
variablePattern,
regionPattern,
libraryIncludePattern,
completionToHover,
signatureToCompletion,
findFilepath,
getIncludeData,
getParams,
getIncludeScripts,
buildFunctionSignature,
functionDefinitionRegex,
};