forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRefactoringUtils.js
More file actions
584 lines (508 loc) · 21.1 KB
/
Copy pathRefactoringUtils.js
File metadata and controls
584 lines (508 loc) · 21.1 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2013 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*
* Utilities functions related to refactoring
*/
define(function (require, exports, module) {
var Acorn = brackets.getModule("thirdparty/acorn/dist/acorn"),
ASTWalker = brackets.getModule("thirdparty/acorn/dist/walk"),
MessageIds = JSON.parse(brackets.getModule("text!JSUtils/MessageIds.json")),
_ = brackets.getModule("thirdparty/lodash"),
AcornLoose = brackets.getModule("thirdparty/acorn/dist/acorn_loose"),
ScopeManager = brackets.getModule("JSUtils/ScopeManager");
var templates = JSON.parse(require("text!Templates.json"));
// Length of the function body used as function name for nameless functions
var FUNCTION_BODY_PREFIX_LENGTH = 30;
/**
* Checks whether two ast nodes are equal
* @param {!ASTNode} a
* @param {!ASTNode} b
* @return {boolean}
*/
function isEqual(a, b) {
return a.start === b.start && a.end === b.end;
}
/**
* Gets a expression surrounding start and end (if any)
* @param {!ASTNode} ast - the ast of the complete file
* @param {!number} start - the start offset
* @param {!number} end - the end offset
* @param {!string} fileText - the entire file text
* @return {ASTNode|boolean}
*/
function getExpression(ast, start, end, fileText) {
var expn = findSurroundExpression(ast, {start: start, end: end});
if (!expn) {
return false;
}
// Class Expression also includes the trailing semicolon
// Add special case for it
if (expn.type === "ClassExpression" && expn.start === start && expn.end - end <= 1) {
expn.end = end;
return expn;
} else if (expn.start === start && expn.end === end) {
return expn;
}
// Subexpressions are possible only for BinaryExpression, LogicalExpression and SequenceExpression
if (!(["BinaryExpression", "LogicalExpression", "SequenceExpression"].includes(expn.type))) {
return false;
}
// Check subexpression
var parentExpn = expn;
var parentExpStr = fileText.substr(parentExpn.start, parentExpn.end - parentExpn.start);
// Check whether the parentExpn forms a valid expression after replacing the sub expression
var str = parentExpStr.substr(0, start - parentExpn.start) + "placeHolder" + parentExpStr.substr(end - parentExpn.start);
var node = isStandAloneExpression(str);
if (node && node.type === parentExpn.type) {
return parentExpn;
}
return false;
}
function getAST(text) {
var ast;
try {
ast = Acorn.parse(text, {ecmaVersion: 9});
} catch(e) {
ast = AcornLoose.parse(text, {ecmaVersion: 9});
}
return ast;
}
/*
* Checks whether the text between start and end offsets form a valid set of statements
* @param {!ASTNode} ast - the ast of the complete file
* @param {!number} start - the start offset
* @param {!number} end - the end offset
* @param {!string} fileText - the entire file text
* @return {boolean}
*/
function checkStatement(ast, start, end, fileText) {
// Do not allow function or class nodes
var notStatement = false;
ASTWalker.simple(getAST(fileText.substr(start, end - start)), {
FunctionDeclaration: function (node) {
notStatement = true;
},
ClassDeclaration: function (node) {
notStatement = true;
}
});
if (notStatement) {
return false;
}
var startStatement = findSurroundASTNode(ast, {start: start}, ["Statement"]);
var endStatement = findSurroundASTNode(ast, {start: end}, ["Statement"]);
return startStatement && endStatement && startStatement.start === start &&
startStatement.end <= end && endStatement.start >= start &&
endStatement.end === end;
}
/**
* Gets a unique identifier name in the scope that starts with prefix
* @param {!Scope} scopes - an array of all scopes returned from tern (each element contains 'props' with identifiers
* in that scope)
* @param {!string} prefix - prefix of the identifier
* @param {number} num - number to start checking for
* @return {!string} identifier name
*/
function getUniqueIdentifierName(scopes, prefix, num) {
if (!scopes) {
return prefix;
}
var props = scopes.reduce(function(props, scope) {
return _.union(props, _.keys(scope.props));
}, []);
if (!props) {
return prefix;
}
num = num || "1";
var name;
while (num < 100) { // limit search length
name = prefix + num;
if (props.indexOf(name) === -1) {
break;
}
++num;
}
return name;
}
/**
* Returns the no of lines in the text
* @param {!string} text
* @return {number}
*/
function numLines(text) {
return text.split("\n").length;
}
/**
* Checks whether the text forms a stand alone expression without considering the context of text
* @param {!string} text
* @return {boolean}
*/
function isStandAloneExpression(text) {
var found = ASTWalker.findNodeAt(getAST(text), 0, text.length, function (nodeType, node) {
if (nodeType === "Expression") {
return true;
}
return false;
});
return found && found.node;
}
/**
* Requests scope data from tern
* @param {!Session} session
* @param {!{line: number, ch: number}} offset
* @return {!$.Promise} a jQuery promise that will be resolved with the scope data
*/
function getScopeData(session, offset) {
var path = session.path,
fileInfo = {
type: MessageIds.TERN_FILE_INFO_TYPE_FULL,
name: path,
offsetLines: 0,
text: ScopeManager.filterText(session.getJavascriptText())
};
ScopeManager.postMessage({
type: MessageIds.TERN_SCOPEDATA_MSG,
fileInfo: fileInfo,
offset: offset
});
var ternPromise = ScopeManager.addPendingRequest(fileInfo.name, offset, MessageIds.TERN_SCOPEDATA_MSG);
var result = new $.Deferred();
ternPromise.done(function (response) {
result.resolveWith(null, [response.scope]);
}).fail(function () {
result.reject();
});
return result;
}
/**
* Normalize text by removing leading and trailing whitespace characters
* and moves the start and end offset to reflect the new offset
* @param {!string} text - selected text
* @param {!number} start - the start offset of the text
* @param {!number} end - the end offset of the text
* @param {!boolean} removeTrailingSemiColons - removes trailing semicolons also if true
* @return {!{text: string, start: number, end: number}}
*/
function normalizeText(text, start, end, removeTrailingSemiColons) {
var trimmedText;
// Remove leading spaces
trimmedText = _.trimLeft(text);
if (trimmedText.length < text.length) {
start += (text.length - trimmedText.length);
}
text = trimmedText;
// Remove trailing spaces
trimmedText = _.trimRight(text);
if (trimmedText.length < text.length) {
end -= (text.length - trimmedText.length);
}
text = trimmedText;
// Remove trailing semicolons
if (removeTrailingSemiColons) {
trimmedText = _.trimRight(text, ';');
if (trimmedText.length < text.length) {
end -= (text.length - trimmedText.length);
}
}
return {
text: trimmedText,
start: start,
end: end
};
}
/**
* Checks whether the scope is a function scope
*/
function isFnScope(scope) {
return !scope.isBlock && !scope.isCatch;
}
function findSurroundExpression(ast, expn) {
var start = expn.start;
var end = expn.end;
var surroundExpn;
while (true) {
surroundExpn = findSurroundASTNode(ast, {start: start, end: end}, ["Expression"]);
if (!surroundExpn) {
return null;
}
// Do not allow sequence expressions
if (surroundExpn.type === "SequenceExpression") {
start = surroundExpn.start - 1;
} else if (surroundExpn.type === "FunctionExpression") { // Do not allow method definition expressions
var methodDefinitionNode = findSurroundASTNode(ast, surroundExpn, ["MethodDefinition"]);
if (methodDefinitionNode && isEqual(methodDefinitionNode.value, surroundExpn)) {
start = surroundExpn.start - 1;
} else {
return surroundExpn;
}
} else {
return surroundExpn;
}
}
return surroundExpn;
}
/**
* Finds the surrounding ast node of the given expression of any of the given types
* @param {!ASTNode} ast
* @param {!{start: number, end: number}} expn - contains start and end offsets of expn
* @param {!Array.<string>} types
* @return {?ASTNode}
*/
function findSurroundASTNode(ast, expn, types) {
var foundNode = ASTWalker.findNodeAround(ast, expn.start, function (nodeType, node) {
if (expn.end) {
return types.includes(nodeType) && node.end >= expn.end;
}
return types.includes(nodeType);
});
return foundNode && _.clone(foundNode.node);
}
/**
* Converts the scopes returned from tern to an array of scopes and adds id and name to the scope
* Also checks for class scopes
* @param {!ASTNode} ast - ast of the complete file
* @param {!Scope} scope - scope returned from tern
* @param {!string} fullText - the complete text of a file
* @return {!Array.<Scope>}
*/
function getAllScopes(ast, scope, fullText) {
var curScope = scope;
var cnt = 0;
var scopes = [];
while (curScope) {
curScope.id = cnt++;
scopes.push(curScope);
if (curScope.fnType) {
// Check for class scopes surrounding the function
if (curScope.fnType === "FunctionExpression") {
var methodDefinitionNode = findSurroundASTNode(ast, curScope.originNode, ["MethodDefinition"]);
// class scope found
if (methodDefinitionNode && isEqual(methodDefinitionNode.value, curScope.originNode)) {
// Change curScope name and originNode to that of methodDefinitionNode
curScope.name = methodDefinitionNode.key.name;
curScope.originNode = methodDefinitionNode;
var classNode = findSurroundASTNode(ast, methodDefinitionNode, ["ClassDeclaration", "ClassExpression"]);
if (classNode) {
// Class Declaration found add it to scopes
var temp = curScope.prev;
var newScope = {};
newScope.isClass = true;
// if the class is class expression, check if it has a name
if (classNode.type === "ClassExpression") {
var assignmentExpNode = findSurroundASTNode(ast, classNode, ["AssignmentExpression"]);
if (assignmentExpNode && assignmentExpNode.left && assignmentExpNode.left.name) {
newScope.name = "class " + assignmentExpNode.left.name;
} else {
var varDeclaratorNode = findSurroundASTNode(ast, classNode, ["VariableDeclarator"]);
if (varDeclaratorNode && varDeclaratorNode.id && varDeclaratorNode.id.name) {
newScope.name = "class " + varDeclaratorNode.id.name;
} else {
newScope.name = "class null";
}
}
} else {
newScope.name = "class " + (classNode.id && classNode.id.name);
}
newScope.originNode = classNode;
curScope.prev = newScope;
newScope.prev = temp;
}
} else {
// For function expressions, assign name to prefix of the function body
curScope.name = "function starting with " +
fullText.substr(
curScope.originNode.body.start,
Math.min(
FUNCTION_BODY_PREFIX_LENGTH,
curScope.originNode.body.end - curScope.originNode.body.start
)
);
}
} else {
// Acorn parse marks name with '✖' under erroneous declarations, check it
if (curScope.fnType === "✖") {
curScope.name = "function starting with " +
fullText.substr(
curScope.originNode.body.start,
Math.min(
FUNCTION_BODY_PREFIX_LENGTH,
curScope.originNode.body.end - curScope.originNode.body.start
)
);
} else {
curScope.name = curScope.fnType;
}
}
} else if (!curScope.originNode) {
curScope.name = "global";
}
curScope = curScope.prev;
}
return scopes;
}
/**
* Note - To use these state defined in Refactoring Session,
* Please reinitialize this RefactoringSession after performing any of the below operations
* (i.e. replaceRange, setSelection or indentLine)
*
* RefactoringSession objects encapsulate state associated with a refactoring session
* and This will help finding information around documents, selection,
* position, ast, and queries around AST nodes
*
* @constructor
* @param {Editor} editor - the editor context for the session
*/
function RefactoringSession(editor) {
this.editor = editor;
this.document = editor.document;
this.selection = editor.getSelection();
this.text = this.document.getText();
this.selectedText = editor.getSelectedText();
this.cm = editor._codeMirror;
this.startIndex = editor.indexFromPos(this.selection.start);
this.endIndex = editor.indexFromPos(this.selection.end);
this.startPos = this.selection.start;
this.endPos = this.selection.end;
this.ast = this.createAstOfCurrentDoc();
}
/**
* Get the end position of given line
*
* @param {number} line - line number
* @return {{line: number, ch: number}} - line end position
*/
RefactoringSession.prototype.lineEndPosition = function (line) {
var lineText = this.document.getLine(line);
return {
line: line,
ch: lineText.length
};
};
/**
* Get the ast of current opened document in focused editor
*
* @return {Object} - Ast of current opened doc
*/
RefactoringSession.prototype.createAstOfCurrentDoc = function () {
var ast,
text = this.document.getText();
try {
ast = Acorn.parse(text);
} catch(e) {
ast = AcornLoose.parse(text);
}
return ast;
};
/**
* This will add template at given position/selection
*
* @param {string} template - name of the template defined in templates.json
* @param {Array} args- Check all arguments that exist in defined templated pass all that args as array
* @param {{line: number, ch: number}} rangeToReplace - Range which we want to replace
* @param {string} subTemplate - If template written under some category
*/
RefactoringSession.prototype.replaceTextFromTemplate = function (template, args, rangeToReplace, subTemplate) {
var templateText = templates[template];
if (subTemplate) {
templateText = templateText[subTemplate];
}
var compiled = _.template(templateText),
formattedText = compiled(args);
if (!rangeToReplace) {
rangeToReplace = this.editor.getSelection();
}
this.document.replaceRange(formattedText, rangeToReplace.start, rangeToReplace.end);
var startLine = rangeToReplace.start.line,
endLine = startLine + formattedText.split("\n").length;
for (var i = startLine + 1; i < endLine; i++) {
this.cm.indentLine(i);
}
};
/**
* Get Params of selected function
*
* @param {number} start- start offset
* @param {number} end - end offset
* @param {string} selectedText - Create ast for only selected node
* @return {Array} param - Array of all parameters in function
*/
RefactoringSession.prototype.getParamsOfFunction = function getParamsOfFunction(start, end, selectedText) {
var param = [];
ASTWalker.simple(AcornLoose.parse(selectedText), {
Function: function (node) {
if (node.type === "FunctionDeclaration") {
node.params.forEach(function (item) {
param.push(item.name);
});
}
}
});
return param;
};
/**
* Get the Parent node
*
* @param {Object} ast - ast of full document
* @param {number} start - start Offset
* @return {Object} node - Returns the parent node of node which is at offset start
*/
RefactoringSession.prototype.getParentNode = function (ast, start) {
var foundNode = ASTWalker.findNodeAround(ast, start, function(nodeType, node) {
return (nodeType === "ObjectExpression");
});
return foundNode && foundNode.node;
};
/**
* Checks weather the node at start is last in that scope or not
*
* @param {Object} ast - ast of full document
* @param {number} start - start Offset
* @return {boolean} - is last node in that scope
*/
RefactoringSession.prototype.isLastNodeInScope = function (ast, start) {
var parentNode = this.getParentNode(ast, start),
currentNodeStart;
ASTWalker.simple(parentNode, {
Property: function (node) {
currentNodeStart = node.start;
}
});
return start >= currentNodeStart;
};
// Define public api
exports.isEqual = isEqual;
exports.getUniqueIdentifierName = getUniqueIdentifierName;
exports.isStandAloneExpression = isStandAloneExpression;
exports.numLines = numLines;
exports.getScopeData = getScopeData;
exports.normalizeText = normalizeText;
exports.getExpression = getExpression;
exports.isFnScope = isFnScope;
exports.getAllScopes = getAllScopes;
exports.checkStatement = checkStatement;
exports.findSurroundASTNode = findSurroundASTNode;
exports.getAST = getAST;
exports.findSurroundExpression = findSurroundExpression;
exports.RefactoringSession = RefactoringSession;
});