This repository has been archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
ScopeManager.js
1537 lines (1348 loc) · 56 KB
/
ScopeManager.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
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013 - present 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.
*
*/
/*
* Throughout this file, the term "outer scope" is used to refer to the outer-
* most/global/root Scope objects for particular file. The term "inner scope"
* is used to refer to a Scope object that is reachable via the child relation
* from an outer scope.
*/
/*global Worker */
define(function (require, exports, module) {
"use strict";
var _ = brackets.getModule("thirdparty/lodash");
var CodeMirror = brackets.getModule("thirdparty/CodeMirror/lib/codemirror"),
DefaultDialogs = brackets.getModule("widgets/DefaultDialogs"),
Dialogs = brackets.getModule("widgets/Dialogs"),
DocumentManager = brackets.getModule("document/DocumentManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
FileUtils = brackets.getModule("file/FileUtils"),
LanguageManager = brackets.getModule("language/LanguageManager"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
Strings = brackets.getModule("strings"),
StringUtils = brackets.getModule("utils/StringUtils");
var HintUtils = require("HintUtils"),
MessageIds = require("MessageIds"),
Preferences = require("Preferences");
var ternEnvironment = [],
pendingTernRequests = {},
builtinFiles = ["ecmascript.json", "browser.json", "jquery.json"],
builtinLibraryNames = [],
isDocumentDirty = false,
_hintCount = 0,
currentWorker = null,
documentChanges = null, // bounds of document changes
preferences = null,
deferredPreferences = null;
var MAX_HINTS = 30, // how often to reset the tern server
LARGE_LINE_CHANGE = 100,
LARGE_LINE_COUNT = 10000,
OFFSET_ZERO = {line: 0, ch: 0};
var config = {};
/**
* An array of library names that contain JavaScript builtins definitions.
*
* @return {Array.<string>} - array of library names.
*/
function getBuiltins() {
return builtinLibraryNames;
}
/**
* Read in the json files that have type information for the builtins, dom,etc
*/
function initTernEnv() {
var path = ExtensionUtils.getModulePath(module, "node_modules/tern/defs/"),
files = builtinFiles,
library;
files.forEach(function (i) {
FileSystem.resolve(path + i, function (err, file) {
if (!err) {
FileUtils.readAsText(file).done(function (text) {
library = JSON.parse(text);
builtinLibraryNames.push(library["!name"]);
ternEnvironment.push(library);
}).fail(function (error) {
console.log("failed to read tern config file " + i);
});
} else {
console.log("failed to read tern config file " + i);
}
});
});
}
initTernEnv();
/**
* Init preferences from a file in the project root or builtin
* defaults if no file is found;
*
* @param {string=} projectRootPath - new project root path. Only needed
* for unit tests.
*/
function initPreferences(projectRootPath) {
// Reject the old preferences if they have not completed.
if (deferredPreferences && deferredPreferences.state() === "pending") {
deferredPreferences.reject();
}
deferredPreferences = $.Deferred();
var pr = ProjectManager.getProjectRoot();
// Open preferences relative to the project root
// Normally there is a project root, but for unit tests we need to
// pass in a project root.
if (pr) {
projectRootPath = pr.fullPath;
} else if (!projectRootPath) {
console.log("initPreferences: projectRootPath has no value");
}
var path = projectRootPath + Preferences.FILE_NAME;
FileSystem.resolve(path, function (err, file) {
if (!err) {
FileUtils.readAsText(file).done(function (text) {
var configObj = null;
try {
configObj = JSON.parse(text);
} catch (e) {
// continue with null configObj which will result in
// default settings.
console.log("Error parsing preference file: " + path);
if (e instanceof SyntaxError) {
console.log(e.message);
}
}
preferences = new Preferences(configObj);
deferredPreferences.resolve();
}).fail(function (error) {
preferences = new Preferences();
deferredPreferences.resolve();
});
} else {
preferences = new Preferences();
deferredPreferences.resolve();
}
});
}
/**
* Will initialize preferences only if they do not exist.
*
*/
function ensurePreferences() {
if (!deferredPreferences) {
initPreferences();
}
}
/**
* Send a message to the tern worker - if the worker is being initialized,
* the message will not be posted until initialization is complete
*/
function postMessage(msg) {
if (currentWorker) {
currentWorker.postMessage(msg);
}
}
/**
* Test if the directory should be excluded from analysis.
*
* @param {!string} path - full directory path.
* @return {boolean} true if excluded, false otherwise.
*/
function isDirectoryExcluded(path) {
var excludes = preferences.getExcludedDirectories();
if (!excludes) {
return false;
}
var testPath = ProjectManager.makeProjectRelativeIfPossible(path);
testPath = FileUtils.stripTrailingSlash(testPath);
return excludes.test(testPath);
}
/**
* Test if the file path is in current editor
*
* @param {string} filePath file path to test for exclusion.
* @return {boolean} true if in editor, false otherwise.
*/
function isFileBeingEdited(filePath) {
var currentEditor = EditorManager.getActiveEditor(),
currentDoc = currentEditor && currentEditor.document;
return (currentDoc && currentDoc.file.fullPath === filePath);
}
/**
* Test if the file path is an internal exclusion.
*
* @param {string} path file path to test for exclusion.
* @return {boolean} true if excluded, false otherwise.
*/
function isFileExcludedInternal(path) {
// The detectedExclusions are files detected to be troublesome with current versions of Tern.
// detectedExclusions is an array of full paths.
var detectedExclusions = PreferencesManager.get("jscodehints.detectedExclusions") || [];
if (detectedExclusions && detectedExclusions.indexOf(path) !== -1) {
return true;
}
return false;
}
/**
* Test if the file should be excluded from analysis.
*
* @param {!File} file - file to test for exclusion.
* @return {boolean} true if excluded, false otherwise.
*/
function isFileExcluded(file) {
if (file.name[0] === ".") {
return true;
}
var languageID = LanguageManager.getLanguageForPath(file.fullPath).getId();
if (languageID !== HintUtils.LANGUAGE_ID) {
return true;
}
var excludes = preferences.getExcludedFiles();
if (excludes && excludes.test(file.name)) {
return true;
}
if (isFileExcludedInternal(file.fullPath)) {
return true;
}
return false;
}
/**
* Add a pending request waiting for the tern-worker to complete.
* If file is a detected exclusion, then reject request.
*
* @param {string} file - the name of the file
* @param {{line: number, ch: number}} offset - the offset into the file the request is for
* @param {string} type - the type of request
* @return {jQuery.Promise} - the promise for the request
*/
function addPendingRequest(file, offset, type) {
var requests,
key = file + "@" + offset.line + "@" + offset.ch,
$deferredRequest;
// Reject detected exclusions
if (isFileExcludedInternal(file)) {
return (new $.Deferred()).reject().promise();
}
if (_.has(pendingTernRequests, key)) {
requests = pendingTernRequests[key];
} else {
requests = {};
pendingTernRequests[key] = requests;
}
if (_.has(requests, type)) {
$deferredRequest = requests[type];
} else {
requests[type] = $deferredRequest = new $.Deferred();
}
return $deferredRequest.promise();
}
/**
* Get any pending $.Deferred object waiting on the specified file and request type
* @param {string} file - the file
* @param {{line: number, ch: number}} offset - the offset into the file the request is for
* @param {string} type - the type of request
* @return {jQuery.Deferred} - the $.Deferred for the request
*/
function getPendingRequest(file, offset, type) {
var key = file + "@" + offset.line + "@" + offset.ch;
if (_.has(pendingTernRequests, key)) {
var requests = pendingTernRequests[key],
requestType = requests[type];
delete pendingTernRequests[key][type];
if (!Object.keys(requests).length) {
delete pendingTernRequests[key];
}
return requestType;
}
}
/**
* @param {string} file a relative path
* @return {string} returns the path we resolved when we tried to parse the file, or undefined
*/
function getResolvedPath(file) {
return currentWorker.getResolvedPath(file);
}
/**
* Get a Promise for the definition from TernJS, for the file & offset passed in.
* @param {{type: string, name: string, offsetLines: number, text: string}} fileInfo
* - type of update, name of file, and the text of the update.
* For "full" updates, the whole text of the file is present. For "part" updates,
* the changed portion of the text. For "empty" updates, the file has not been modified
* and the text is empty.
* @param {{line: number, ch: number}} offset - the offset in the file the hints should be calculate at
* @return {jQuery.Promise} - a promise that will resolve to definition when
* it is done
*/
function getJumptoDef(fileInfo, offset) {
postMessage({
type: MessageIds.TERN_JUMPTODEF_MSG,
fileInfo: fileInfo,
offset: offset
});
return addPendingRequest(fileInfo.name, offset, MessageIds.TERN_JUMPTODEF_MSG);
}
/**
* check to see if the text we are sending to Tern is too long.
* @param {string} the text to check
* @return {string} the text, or the empty text if the original was too long
*/
function filterText(text) {
var newText = text;
if (text.length > preferences.getMaxFileSize()) {
newText = "";
}
return newText;
}
/**
* Get the text of a document, applying any size restrictions
* if necessary
* @param {Document} document - the document to get the text from
* @return {string} the text, or the empty text if the original was too long
*/
function getTextFromDocument(document) {
var text = document.getText();
text = filterText(text);
return text;
}
/**
* Request Jump-To-Definition from Tern.
*
* @param {session} session - the session
* @param {Document} document - the document
* @param {{line: number, ch: number}} offset - the offset into the document
* @return {jQuery.Promise} - The promise will not complete until tern
* has completed.
*/
function requestJumptoDef(session, document, offset) {
var path = document.file.fullPath,
fileInfo = {type: MessageIds.TERN_FILE_INFO_TYPE_FULL,
name: path,
offsetLines: 0,
text: filterText(session.getJavascriptText())};
var ternPromise = getJumptoDef(fileInfo, offset);
return {promise: ternPromise};
}
/**
* Handle the response from the tern web worker when
* it responds with the definition
*
* @param response - the response from the worker
*/
function handleJumptoDef(response) {
var file = response.file,
offset = response.offset;
var $deferredJump = getPendingRequest(file, offset, MessageIds.TERN_JUMPTODEF_MSG);
if ($deferredJump) {
response.fullPath = getResolvedPath(response.resultFile);
$deferredJump.resolveWith(null, [response]);
}
}
/**
* Get a Promise for the completions from TernJS, for the file & offset passed in.
*
* @param {{type: string, name: string, offsetLines: number, text: string}} fileInfo
* - type of update, name of file, and the text of the update.
* For "full" updates, the whole text of the file is present. For "part" updates,
* the changed portion of the text. For "empty" updates, the file has not been modified
* and the text is empty.
* @param {{line: number, ch: number}} offset - the offset in the file the hints should be calculate at
* @param {boolean} isProperty - true if getting a property hint,
* otherwise getting an identifier hint.
* @return {jQuery.Promise} - a promise that will resolve to an array of completions when
* it is done
*/
function getTernHints(fileInfo, offset, isProperty) {
/**
* If the document is large and we have modified a small portions of it that
* we are asking hints for, then send a partial document.
*/
postMessage({
type: MessageIds.TERN_COMPLETIONS_MSG,
fileInfo: fileInfo,
offset: offset,
isProperty: isProperty
});
return addPendingRequest(fileInfo.name, offset, MessageIds.TERN_COMPLETIONS_MSG);
}
/**
* Get a Promise for the function type from TernJS.
* @param {{type: string, name: string, offsetLines: number, text: string}} fileInfo
* - type of update, name of file, and the text of the update.
* For "full" updates, the whole text of the file is present. For "part" updates,
* the changed portion of the text. For "empty" updates, the file has not been modified
* and the text is empty.
* @param {{line:number, ch:number}} offset - the line, column info for what we want the function type of.
* @return {jQuery.Promise} - a promise that will resolve to the function type of the function being called.
*/
function getTernFunctionType(fileInfo, offset) {
postMessage({
type: MessageIds.TERN_CALLED_FUNC_TYPE_MSG,
fileInfo: fileInfo,
offset: offset
});
return addPendingRequest(fileInfo.name, offset, MessageIds.TERN_CALLED_FUNC_TYPE_MSG);
}
/**
* Given a starting and ending position, get a code fragment that is self contained
* enough to be compiled.
*
* @param {!Session} session - the current session
* @param {{line: number, ch: number}} start - the starting position of the changes
* @return {{type: string, name: string, offsetLines: number, text: string}}
*/
function getFragmentAround(session, start) {
var minIndent = null,
minLine = null,
endLine,
cm = session.editor._codeMirror,
tabSize = cm.getOption("tabSize"),
document = session.editor.document,
p,
min,
indent,
line;
// expand range backwards
for (p = start.line - 1, min = Math.max(0, p - 100); p >= min; --p) {
line = session.getLine(p);
var fn = line.search(/\bfunction\b/);
if (fn >= 0) {
indent = CodeMirror.countColumn(line, null, tabSize);
if (minIndent === null || minIndent > indent) {
if (session.getToken({line: p, ch: fn + 1}).type === "keyword") {
minIndent = indent;
minLine = p;
}
}
}
}
if (minIndent === null) {
minIndent = 0;
}
if (minLine === null) {
minLine = min;
}
var max = Math.min(cm.lastLine(), start.line + 100),
endCh = 0;
for (endLine = start.line + 1; endLine < max; ++endLine) {
line = cm.getLine(endLine);
if (line.length > 0) {
indent = CodeMirror.countColumn(line, null, tabSize);
if (indent <= minIndent) {
endCh = line.length;
break;
}
}
}
var from = {line: minLine, ch: 0},
to = {line: endLine, ch: endCh};
return {type: MessageIds.TERN_FILE_INFO_TYPE_PART,
name: document.file.fullPath,
offsetLines: from.line,
text: document.getRange(from, to)};
}
/**
* Get an object that describes what tern needs to know about the updated
* file to produce a hint. As a side-effect of this calls the document
* changes are reset.
*
* @param {!Session} session - the current session
* @param {boolean=} preventPartialUpdates - if true, disallow partial updates.
* Optional, defaults to false.
* @return {{type: string, name: string, offsetLines: number, text: string}}
*/
function getFileInfo(session, preventPartialUpdates) {
var start = session.getCursor(),
end = start,
document = session.editor.document,
path = document.file.fullPath,
isHtmlFile = LanguageManager.getLanguageForPath(path).getId() === "html",
result;
if (isHtmlFile) {
result = {type: MessageIds.TERN_FILE_INFO_TYPE_FULL,
name: path,
text: session.getJavascriptText()};
} else if (!documentChanges) {
result = {type: MessageIds.TERN_FILE_INFO_TYPE_EMPTY,
name: path,
text: ""};
} else if (!preventPartialUpdates && session.editor.lineCount() > LARGE_LINE_COUNT &&
(documentChanges.to - documentChanges.from < LARGE_LINE_CHANGE) &&
documentChanges.from <= start.line &&
documentChanges.to > end.line) {
result = getFragmentAround(session, start);
} else {
result = {type: MessageIds.TERN_FILE_INFO_TYPE_FULL,
name: path,
text: getTextFromDocument(document)};
}
documentChanges = null;
return result;
}
/**
* Get the current offset. The offset is adjusted for "part" updates.
*
* @param {!Session} session - the current session
* @param {{type: string, name: string, offsetLines: number, text: string}} fileInfo
* - type of update, name of file, and the text of the update.
* For "full" updates, the whole text of the file is present. For "part" updates,
* the changed portion of the text. For "empty" updates, the file has not been modified
* and the text is empty.
* @param {{line: number, ch: number}=} offset - the default offset (optional). Will
* use the cursor if not provided.
* @return {{line: number, ch: number}}
*/
function getOffset(session, fileInfo, offset) {
var newOffset;
if (offset) {
newOffset = {line: offset.line, ch: offset.ch};
} else {
newOffset = session.getCursor();
}
if (fileInfo.type === MessageIds.TERN_FILE_INFO_TYPE_PART) {
newOffset.line = Math.max(0, newOffset.line - fileInfo.offsetLines);
}
return newOffset;
}
/**
* Get a Promise for all of the known properties from TernJS, for the directory and file.
* The properties will be used as guesses in tern.
* @param {Session} session - the active hinting session
* @param {Document} document - the document for which scope info is
* desired
* @return {jQuery.Promise} - The promise will not complete until the tern
* request has completed.
*/
function requestGuesses(session, document) {
var $deferred = $.Deferred(),
fileInfo = getFileInfo(session),
offset = getOffset(session, fileInfo);
postMessage({
type: MessageIds.TERN_GET_GUESSES_MSG,
fileInfo: fileInfo,
offset: offset
});
var promise = addPendingRequest(fileInfo.name, offset, MessageIds.TERN_GET_GUESSES_MSG);
promise.done(function (guesses) {
session.setGuesses(guesses);
$deferred.resolve();
}).fail(function () {
$deferred.reject();
});
return $deferred.promise();
}
/**
* Handle the response from the tern web worker when
* it responds with the list of completions
*
* @param {{file: string, offset: {line: number, ch: number}, completions:Array.<string>,
* properties:Array.<string>}} response - the response from the worker
*/
function handleTernCompletions(response) {
var file = response.file,
offset = response.offset,
completions = response.completions,
properties = response.properties,
fnType = response.fnType,
type = response.type,
error = response.error,
$deferredHints = getPendingRequest(file, offset, type);
if ($deferredHints) {
if (error) {
$deferredHints.reject();
} else if (completions) {
$deferredHints.resolveWith(null, [{completions: completions}]);
} else if (properties) {
$deferredHints.resolveWith(null, [{properties: properties}]);
} else if (fnType) {
$deferredHints.resolveWith(null, [fnType]);
}
}
}
/**
* Handle the response from the tern web worker when
* it responds to the get guesses message.
*
* @param {{file: string, type: string, offset: {line: number, ch: number},
* properties: Array.<string>}} response -
* the response from the worker contains the guesses for a
* property lookup.
*/
function handleGetGuesses(response) {
var path = response.file,
type = response.type,
offset = response.offset,
$deferredHints = getPendingRequest(path, offset, type);
if ($deferredHints) {
$deferredHints.resolveWith(null, [response.properties]);
}
}
/**
* Handle the response from the tern web worker when
* it responds to the update file message.
*
* @param {{path: string, type: string}} response - the response from the worker
*/
function handleUpdateFile(response) {
var path = response.path,
type = response.type,
$deferredHints = getPendingRequest(path, OFFSET_ZERO, type);
if ($deferredHints) {
$deferredHints.resolve();
}
}
/**
* Handle timed out inference
*
* @param {{path: string, type: string}} response - the response from the worker
*/
function handleTimedOut(response) {
var detectedExclusions = PreferencesManager.get("jscodehints.detectedExclusions") || [],
filePath = response.file;
// Don't exclude the file currently being edited
if (isFileBeingEdited(filePath)) {
return;
}
// Handle file that is already excluded
if (detectedExclusions.indexOf(filePath) !== -1) {
console.log("JavaScriptCodeHints.handleTimedOut: file already in detectedExclusions array timed out: " + filePath);
return;
}
// Save detected exclusion in project prefs so no further time is wasted on it
detectedExclusions.push(filePath);
PreferencesManager.set("jscodehints.detectedExclusions", detectedExclusions, { location: { scope: "project" } });
// Show informational dialog
Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_INFO,
Strings.DETECTED_EXCLUSION_TITLE,
StringUtils.format(
Strings.DETECTED_EXCLUSION_INFO,
StringUtils.breakableUrl(filePath)
),
[
{
className : Dialogs.DIALOG_BTN_CLASS_PRIMARY,
id : Dialogs.DIALOG_BTN_OK,
text : Strings.OK
}
]
);
}
/**
* Encapsulate all the logic to talk to the worker thread. This will create
* a new instance of a TernWorker, which the rest of the hinting code can use to talk
* to the worker, without worrying about initialization, priming the pump, etc.
*
*/
function TernWorker() {
var ternPromise = null,
addFilesPromise = null,
rootTernDir = null,
projectRoot = null,
stopAddingFiles = false,
resolvedFiles = {}, // file -> resolved file
numInitialFiles = 0,
numResolvedFiles = 0,
numAddedFiles = 0,
_ternWorker = null;
/**
* @param {string} file a relative path
* @return {string} returns the path we resolved when we tried to parse the file, or undefined
*/
function getResolvedPath(file) {
return resolvedFiles[file];
}
/**
* Determine whether the current set of files are using modules to pull in
* additional files.
*
* @return {boolean} - true if more files than the current directory have
* been read in.
*/
function usingModules() {
return numInitialFiles !== numResolvedFiles;
}
/**
* Send a message to the tern worker - if the worker is being initialized,
* the message will not be posted until initialization is complete
*/
function postMessage(msg) {
addFilesPromise.done(function (ternWorker) {
// If an error came up during file handling, bail out now
if (!ternWorker) {
return;
}
if (config.debug) {
console.debug("Sending message", msg);
}
ternWorker.postMessage(msg);
});
}
/**
* Send a message to the tern worker - this is only for messages that
* need to be sent before and while the addFilesPromise is being resolved.
*/
function _postMessageByPass(msg) {
ternPromise.done(function (ternWorker) {
if (config.debug) {
console.debug("Sending message", msg);
}
ternWorker.postMessage(msg);
});
}
/**
* Update tern with the new contents of a given file.
*
* @param {Document} document - the document to update
* @return {jQuery.Promise} - the promise for the request
*/
function updateTernFile(document) {
var path = document.file.fullPath;
_postMessageByPass({
type : MessageIds.TERN_UPDATE_FILE_MSG,
path : path,
text : getTextFromDocument(document)
});
return addPendingRequest(path, OFFSET_ZERO, MessageIds.TERN_UPDATE_FILE_MSG);
}
/**
* Handle a request from the worker for text of a file
*
* @param {{file:string}} request - the request from the worker. Should be an Object containing the name
* of the file tern wants the contents of
*/
function handleTernGetFile(request) {
function replyWith(name, txt) {
_postMessageByPass({
type: MessageIds.TERN_GET_FILE_MSG,
file: name,
text: txt
});
}
var name = request.file;
/**
* Helper function to get the text of a given document and send it to tern.
* If DocumentManager successfully gets the file's text then we'll send it to the tern worker.
* The Promise for getDocumentText() is returned so that custom fail functions can be used.
*
* @param {string} filePath - the path of the file to get the text of
* @return {jQuery.Promise} - the Promise returned from DocumentMangaer.getDocumentText()
*/
function getDocText(filePath) {
if (!FileSystem.isAbsolutePath(filePath) || // don't handle URLs
filePath.slice(0, 2) === "//") { // don't handle protocol-relative URLs like //example.com/main.js (see #10566)
return (new $.Deferred()).reject().promise();
}
var file = FileSystem.getFileForPath(filePath),
promise = DocumentManager.getDocumentText(file);
promise.done(function (docText) {
resolvedFiles[name] = filePath;
numResolvedFiles++;
replyWith(name, filterText(docText));
});
return promise;
}
/**
* Helper function to find any files in the project that end with the
* name we are looking for. This is so we can find requirejs modules
* when the baseUrl is unknown, or when the project root is not the same
* as the script root (e.g. if you open the 'brackets' dir instead of 'brackets/src' dir).
*/
function findNameInProject() {
// check for any files in project that end with the right path.
var fileName = name.substring(name.lastIndexOf("/") + 1);
function _fileFilter(entry) {
return entry.name === fileName;
}
ProjectManager.getAllFiles(_fileFilter).done(function (files) {
var file;
files = files.filter(function (file) {
var pos = file.fullPath.length - name.length;
return pos === file.fullPath.lastIndexOf(name);
});
if (files.length === 1) {
file = files[0];
}
if (file) {
getDocText(file.fullPath).fail(function () {
replyWith(name, "");
});
} else {
replyWith(name, "");
}
});
}
if (!isFileExcludedInternal(name)) {
getDocText(name).fail(function () {
getDocText(rootTernDir + name).fail(function () {
// check relative to project root
getDocText(projectRoot + name)
// last look for any files that end with the right path
// in the project
.fail(findNameInProject);
});
});
}
}
/**
* Prime the pump for a fast first lookup.
*
* @param {string} path - full path of file
* @return {jQuery.Promise} - the promise for the request
*/
function primePump(path) {
_postMessageByPass({
type : MessageIds.TERN_PRIME_PUMP_MSG,
path : path
});
return addPendingRequest(path, OFFSET_ZERO, MessageIds.TERN_PRIME_PUMP_MSG);
}
/**
* Handle the response from the tern web worker when
* it responds to the prime pump message.
*
* @param {{path: string, type: string}} response - the response from the worker
*/
function handlePrimePumpCompletion(response) {
var path = response.path,
type = response.type,
$deferredHints = getPendingRequest(path, OFFSET_ZERO, type);
if ($deferredHints) {
$deferredHints.resolve();
}
}
/**
* Add new files to tern, keeping any previous files.
* The tern server must be initialized before making
* this call.
*
* @param {Array.<string>} files - array of file to add to tern.
* @return {boolean} - true if more files may be added, false if maximum has been reached.
*/
function addFilesToTern(files) {
// limit the number of files added to tern.
var maxFileCount = preferences.getMaxFileCount();
if (numResolvedFiles + numAddedFiles < maxFileCount) {
var available = maxFileCount - numResolvedFiles - numAddedFiles;
if (available < files.length) {
files = files.slice(0, available);
}
numAddedFiles += files.length;
ternPromise.done(function (worker) {
var msg = {
type : MessageIds.TERN_ADD_FILES_MSG,
files : files
};
if (config.debug) {
console.debug("Sending message", msg);
}
worker.postMessage(msg);
});
} else {
stopAddingFiles = true;
}
return stopAddingFiles;
}
/**
* Add the files in the directory and subdirectories of a given directory
* to tern.
*
* @param {string} dir - the root directory to add.
* @param {function ()} doneCallback - called when all files have been
* added to tern.
*/