Use tern to sort ids by depth, remove scope info

This commit is contained in:
dloverin committed 2013-03-28 15:06:15 -04:00
1 parent 33579f69d2
commit 7bfaedfa0a
5 files changed
+88 -434

No files matched your search

@@ -48,10 +48,6 @@ define(function (require, exports, module) {
ternEnvironment = [],
pendingTernRequests = {},
rootTernDir = null,
outerScopeWorker = (function () {
var path = module.uri.substring(0, module.uri.lastIndexOf("/") + 1);
return new Worker(path + "parser-worker.js");
}()),
ternWorker = (function () {
var path = module.uri.substring(0, module.uri.lastIndexOf("/") + 1);
return new Worker(path + "tern-worker.js");
@@ -191,15 +187,6 @@ define(function (require, exports, module) {
// the file will be clean since the last outer scope request
state.dirtyFile = false;
// send text to the parser worker
outerScopeWorker.postMessage({
type : HintUtils.SCOPE_MSG_TYPE,
dir : dir,
file : file,
text : text,
force : !state.scope
});
}
}
state.text = text;
@@ -223,128 +210,6 @@ define(function (require, exports, module) {
*/
function refreshInnerScope(dir, file, offset) {
/*
* Filter a list of tokens using a given scope object
*
* @param {Array.<Object>} tokens - a list of identifier tokens
* @param {Scope} scope - a scope object
* @return {Array.<Object>} - the sublist of the input list that
* contains all and only the identifier tokens in scope
* w.r.t. to the given scope
*/
function filterByScope(tokens, scope) {
return tokens.filter(function (id) {
var level = scope.contains(id.value);
return (level >= 0);
});
}
/*
* Combine a particular property from a set of sets using a given add
* operation
*
* @param {Object} sets - a set of sets
* @param {string} propName - the property to pick out from each set
* @param {Function} add - the function that combines properties from
* each set
* @return {Object}- the result of combining each set's property using
* the add function
*/
function merge(sets, propName, add) {
var combinedSet = {},
nextSet,
file;
for (file in sets) {
if (sets.hasOwnProperty(file)) {
nextSet = sets[file][propName];
if (nextSet) {
add(combinedSet, nextSet);
}
}
}
return combinedSet;
}
/*
* Combine properties from files in the current file's directory into
* a single list.
*
* @param {string} dir - the directory name of the files for which
* property lists should be merged
* @param {Array.<Object>} - the combined list of property tokens
*/
function mergeProperties(dir) {
function addPropObjs(obj1, obj2) {
function addToObj(obj, token) {
if (!Object.prototype.hasOwnProperty.call(obj, token.value)) {
obj[token.value] = token;
}
}
obj2.forEach(function (token) {
addToObj(obj1, token);
});
}
var stateMap = getFileState(dir),
propObj = merge(stateMap, "properties", addPropObjs),
propList = [],
propName;
for (propName in propObj) {
if (Object.prototype.hasOwnProperty.call(propObj, propName)) {
propList.push(propObj[propName]);
}
}
return propList;
}
/*
* Combine association set objects from all of the files in a given
* directory
*
* @param {string} dir - the directory name of the files for which
* association sets should be merged
* @param {Object} - the combined association set object
*/
function mergeAssociations(dir) {
function addAssocSets(list1, list2) {
var name;
function addAssocObjs(assoc1, assoc2) {
var name;
for (name in assoc2) {
if (Object.prototype.hasOwnProperty.call(assoc2, name)) {
if (Object.prototype.hasOwnProperty.call(assoc1, name)) {
assoc1[name] = assoc1[name] + assoc2[name];
} else {
assoc1[name] = assoc2[name];
}
}
}
}
for (name in list2) {
if (Object.prototype.hasOwnProperty.call(list2, name)) {
if (Object.prototype.hasOwnProperty.call(list1, name)) {
addAssocObjs(list1[name], list2[name]);
} else {
list1[name] = list2[name];
}
}
}
}
var stateMap = getFileState(dir);
return merge(stateMap, "associations", addAssocSets);
}
var state = getFileState(dir, file);
// If there is no outer scope, the inner scope request is deferred.
@@ -425,27 +290,13 @@ define(function (require, exports, module) {
dir = split.dir,
file = split.file;
var $deferredHints = $.Deferred();
var $deferredHints = $.Deferred(),
ternPromise = getTernHints("dir", "file", offset, document.getText());
var scopeInfo = refreshInnerScope(dir, file, offset);
var scopePromise;
if( scopeInfo.hasOwnProperty("promise") ) {
scopePromise = scopeInfo.promise;
}
else {
// make a scopePromise that we can pass to when below
var $scopeInfo = $.Deferred();
scopePromise = $scopeInfo.promise();
$scopeInfo.resolveWith(null, [scopeInfo]);
}
var ternPromise = getTernHints("dir", "file", offset, document.getText());
$.when(scopePromise, ternPromise).done(
function(scopeInfo, ternHints){
$.when(ternPromise).done(
function(ternHints){
session.setTernHints(ternHints);
$deferredHints.resolveWith(null, [scopeInfo]);
$deferredHints.resolveWith(null);
});
return {promise:$deferredHints.promise()};
}
@@ -654,18 +505,6 @@ define(function (require, exports, module) {
}
}
// handle response objects, otherwise log the message
outerScopeWorker.addEventListener("message", function (e) {
var response = e.data,
type = response.type;
if (type === HintUtils.SCOPE_MSG_TYPE) {
handleOuterScope(response);
} else {
console.log("Worker: " + (response.log || response));
}
});
ternWorker.addEventListener("message", function (e) {
var response = e.data,
type = response.type;
@@ -263,117 +263,16 @@ define(function (require, exports, module) {
*/
Session.prototype.getHints = function () {
/*
* Comparator for sorting tokens according to minimum distance from
* a given position
*
* @param {number} pos - the position to which a token's occurrences
* are compared
* @param {Function} - the comparator function
/**
* sort by scope depth.
*
* @param a
* @param b
* @return {*}
*/
function compareByPosition(pos) {
/*
* Compute the minimum distance between a token, with which is
* associated a sorted list of positions, and a given offset.
*
* @param {number} pos - the position to which a token's occurrences
* are compared.
* @param {Object} token - a hint token, annotated with a list of
* occurrence positions
* @return number - the least distance of an occurrence of token to
* pos, or Infinity if there are no occurrences
*/
function minDistToPos(pos, token) {
var arr = token.positions,
low = 0,
high = arr.length,
middle = Math.floor(high / 2),
dist;
if (high === 0) {
return Infinity;
} else {
// binary search for the position
while (low < middle && middle < high) {
if (arr[middle] < pos) {
low = middle;
middle += Math.floor((high - middle) / 2);
} else if (arr[middle] > pos) {
high = middle;
middle = low + Math.floor((middle - low) / 2);
} else {
break;
}
}
// the closest position is off by no more than one
dist = Math.abs(arr[middle] - pos);
if (middle > 0) {
dist = Math.min(dist, Math.abs(arr[middle - 1] - pos));
}
if (middle + 1 < arr.length) {
dist = Math.min(dist, Math.abs(arr[middle + 1] - pos));
}
return dist;
}
}
return function (a, b) {
/*
* Look up the cached minimum distance from an occurrence of
* the token to the given position, calculating and storing it
* if needed.
*
* @param {Object} token - the token from which the minimum
* distance to position pos is required
* @return {number} - the least distance of an occurrence of
* token to position pos
*/
function getDistToPos(token) {
var dist;
if (token.distToPos >= 0) {
dist = token.distToPos;
} else {
dist = minDistToPos(pos, token);
token.distToPos = dist;
}
return dist;
}
var aDist = getDistToPos(a),
bDist = getDistToPos(b);
if (aDist === Infinity) {
if (bDist === Infinity) {
return 0;
} else {
return 1;
}
} else {
if (bDist === Infinity) {
return -1;
} else {
return aDist - bDist;
}
}
};
}
/*
* Comparator for sorting tokens lexicographically according to scope,
* assuming the scope level has already been annotated.
*
* @param {Object} a - a token
* @param {Object} b - another token
* @param {number} - comparator value that indicates whether a is more
* tightly scoped than b
*/
function compareByScope(a, b) {
var adepth = a.level;
var bdepth = b.level;
function compareByScopeDepth(a, b) {
var adepth = a.depth;
var bdepth = b.depth;
if (adepth >= 0) {
if (bdepth >= 0) {
@@ -381,15 +280,13 @@ define(function (require, exports, module) {
} else {
return -1;
}
} else if (bdepth >= 0) {
return 1;
} else {
if (bdepth >= 0) {
return 1;
} else {
return 0;
}
return 0;
}
}
/*
* Comparator for sorting tokens by name
*
@@ -399,64 +296,18 @@ define(function (require, exports, module) {
* of token a is lexicographically lower than the name of token b
*/
function compareByName(a, b) {
if (a.value === b.value) {
var aLowerCase = a.value.toLowerCase();
var bLowerCase = b.value.toLowerCase();
if (aLowerCase === bLowerCase) {
return 0;
} else if (a.value < b.value) {
} else if (aLowerCase < bLowerCase) {
return -1;
} else {
return 1;
}
}
/*
* Comparator for sorting tokens by path, such that a <= b if
* a.path === path
*
* @param {string} path - the target path name
* @return {Function} - the comparator function
*/
function compareByPath(path) {
return function (a, b) {
if (a.path === path) {
if (b.path === path) {
return 0;
} else {
return -1;
}
} else {
if (b.path === path) {
return 1;
} else {
return 0;
}
}
};
}
/*
* Comparator for sorting properties w.r.t. an association object.
*
* @param {Object} assoc - an association object
* @return {Function} - the comparator function
*/
function compareByAssociation(assoc) {
return function (a, b) {
if (Object.prototype.hasOwnProperty.call(assoc, a.value)) {
if (Object.prototype.hasOwnProperty.call(assoc, b.value)) {
return assoc[a.value] - assoc[b.value];
} else {
return -1;
}
} else {
if (Object.prototype.hasOwnProperty.call(assoc, b.value)) {
return 1;
} else {
return 0;
}
}
};
}
/*
* Forms the lexicographical composition of comparators, i.e.,
* "a lex(c1,c2) b" iff "a c1 b or (a = b and a c2 b)"
@@ -479,57 +330,12 @@ define(function (require, exports, module) {
/*
* A comparator for identifiers: the lexicographic combination of
* scope, position and name.
*
* @param {number} pos - the target position by which identifiers are
* compared
* scope and name.
*
* @return {Function} - the comparator function
*/
function compareIdentifiers(pos) {
return lexicographic(compareByScope,
lexicographic(compareByPosition(pos),
compareByName));
}
/*
* A comparator for properties: the lexicographic combination of
* association, path name, position, and name.
*
* @param {Object} assoc - the association by which properties are
* compared
* @param {string} path - the path name by which properties are
* compared
* @param {number} pos - the target position by which properties are
* compared
* @return {Function} - the comparator function
*/
function compareProperties(assoc, path, pos) {
return lexicographic(compareByAssociation(assoc),
lexicographic(compareByPath(path),
lexicographic(compareByPosition(pos),
compareByName)));
}
/*
* Clone a list of hints. (Used so that later annotations are not
* preserved when scope information changes.)
*
* @param {Array.<Object>} hints - an array of hint tokens
* @return {Array.<Object>} - a new array of objects that are clones of
* the objects in the input array
*/
function copyHints(hints) {
function cloneToken(token) {
var copy = {},
prop;
for (prop in token) {
if (Object.prototype.hasOwnProperty.call(token, prop)) {
copy[prop] = token[prop];
}
}
return copy;
}
return hints.map(cloneToken);
function compareIdentifiers() {
return lexicographic(compareByScopeDepth, compareByName);
}
var cursor = this.editor.getCursorPos(),
@@ -538,30 +344,15 @@ define(function (require, exports, module) {
association,
hints;
var ternHints = this.ternHints;
if (type.property) {
var ternHints = this.ternHints;
//console.log("Got " + (ternHints ? ternHints.length : 0) + " hints from tern");
if( ternHints && ternHints.length > 0 ) {
hints = ternHints;
hints.sort(compareByName);
}
else{
hints = copyHints(this.properties);
if (type.context &&
Object.prototype.hasOwnProperty.call(this.associations, type.context)) {
association = this.associations[type.context];
hints = HintUtils.annotateWithAssociation(hints, association);
hints.sort(compareProperties(association, this.path, offset));
} else {
hints.sort(compareProperties({}, this.path, offset));
}
}
} else {
hints = copyHints(this.identifiers);
hints = HintUtils.annotateWithScope(hints, this.scope);
hints = hints.concat(this.literals);
hints.sort(compareIdentifiers(offset));
hints = hints.concat(this.globals);
hints = ternHints ? ternHints : [];
hints.sort(compareIdentifiers());
hints = hints.concat(HintUtils.LITERALS);
hints = hints.concat(HintUtils.KEYWORDS);
}
@@ -39,7 +39,6 @@ define(function (require, exports, module) {
var session = null, // object that encapsulates the current session state
cachedHints = null, // sorted hints for the current hinting session
cachedType = null, // describes the lookup type and the object context
cachedScope = null, // the inner-most scope returned by the query worker
cachedLine = null; // the line number for the cached scope
var MAX_DISPLAYED_HINTS = 100,
@@ -52,9 +51,10 @@ define(function (require, exports, module) {
*
* @param {Array.<Object>} hints - hints to be included in the response
* @param {string} query - querystring with which to filter the hint list
* @param {Object} type - the type of query, property vs. identifier
* @return {Object} - hint response as defined by the CodeHintManager API
*/
function getHintResponse(hints, query) {
function getHintResponse(hints, query, type) {
var trimmedQuery,
filteredHints,
@@ -136,7 +136,7 @@ define(function (require, exports, module) {
* @param {Array.<Object>} hints - the list of hints to format
* @param {string} query - querystring used for highlighting matched
* poritions of each hint
* @param {Array.<jQuery.Object>} - array of hints formatted as jQuery
* @return {Array.<jQuery.Object>} - array of hints formatted as jQuery
* objects
*/
function formatHints(hints, query) {
@@ -162,18 +162,26 @@ define(function (require, exports, module) {
delimiter = "";
// level indicates either variable scope or property confidence
switch (token.level) {
case 0:
$hintObj.addClass("priority-high");
break;
case 1:
$hintObj.addClass("priority-medium");
break;
case 2:
$hintObj.addClass("priority-low");
break;
if (!type.property && token.depth !== undefined) {
switch (token.depth) {
case 0:
$hintObj.addClass("priority-high");
break;
case 1:
$hintObj.addClass("priority-medium");
break;
case 2:
$hintObj.addClass("priority-low");
break;
default:
$hintObj.addClass("priority-lowest");
break;
}
}
if (token.guess)
$hintObj.addClass("guess-hint");
// is the token a global variable?
if (token.global) {
$hintObj.addClass("global-hint");
@@ -224,8 +232,13 @@ define(function (require, exports, module) {
trimmedQuery = query;
}
filteredHints = filterWithQuery(hints, MAX_DISPLAYED_HINTS);
formattedHints = formatHints(filteredHints, trimmedQuery);
if (hints) {
filteredHints = filterWithQuery(hints, MAX_DISPLAYED_HINTS);
formattedHints = formatHints(filteredHints, trimmedQuery);
}
else {
formattedHints = [];
}
return {
hints: formattedHints,
@@ -254,17 +267,19 @@ define(function (require, exports, module) {
// don't autocomplete within strings or comments, etc.
if (token && HintUtils.hintable(token)) {
var offset = session.getOffset();
var offset = session.getOffset(),
type = session.getType(),
query = session.getQuery();
// Invalidate cached information if: 1) no scope exists; 2) the
// cursor has moved a line; 3) the scope is dirty; or 4) if the
// cursor has moved into a different scope. Cached information
// is also reset on editor change.
if (!cachedScope ||
if (!cachedHints ||
cachedLine !== cursor.line ||
ScopeManager.isScopeDirty(session.editor.document) ||
!cachedScope.containsPositionImmediate(offset)) {
cachedScope = null;
type.property !== cachedType.property ||
type.context !== cachedType.context) {
//console.log("clear hints");
cachedLine = null;
cachedHints = null;
}
@@ -292,18 +307,18 @@ define(function (require, exports, module) {
// Compute fresh hints if none exist, or if the session
// type has changed since the last hint computation
if (!cachedScope ||
if (!cachedHints ||
type.property !== cachedType.property ||
type.context !== cachedType.context) {
type.context !== cachedType.context ||
query.length == 0 ||
(cachedHints.length = 0 && query.length == 2)) { // FIXME: length of 2 is special because that is when tern starts guessing
var offset = session.getOffset(),
scopeResponse = ScopeManager.getScopeInfo(session, session.editor.document, offset),
self = this;
if (scopeResponse.hasOwnProperty("promise")) {
var $deferredHints = $.Deferred();
scopeResponse.promise.done(function (scopeInfo) {
session.setScopeInfo(scopeInfo);
cachedScope = scopeInfo.scope;
scopeResponse.promise.done(function () {
cachedLine = cursor.line;
cachedType = session.getType();
cachedHints = session.getHints();
@@ -312,7 +327,7 @@ define(function (require, exports, module) {
if ($deferredHints.state() === "pending") {
var query = session.getQuery(),
hintResponse = getHintResponse(cachedHints, query);
hintResponse = getHintResponse(cachedHints, query, type);
$deferredHints.resolveWith(null, [hintResponse]);
$(self).triggerHandler("hintResponse", [query]);
@@ -326,13 +341,11 @@ define(function (require, exports, module) {
$(this).triggerHandler("deferredResponse");
return $deferredHints;
} else {
session.setScopeInfo(scopeResponse);
cachedScope = scopeResponse.scope;
cachedLine = cursor.line;
}
}
if (cachedScope) {
if (cachedHints) {
var type = session.getType(),
query = session.getQuery();
@@ -344,7 +357,7 @@ define(function (require, exports, module) {
cachedType = type;
cachedHints = session.getHints();
}
return getHintResponse(cachedHints, query);
return getHintResponse(cachedHints, query, type);
}
}
}
@@ -426,7 +439,6 @@ define(function (require, exports, module) {
*/
function installEditorListeners(editor) {
// always clean up cached scope and hint info
cachedScope = null;
cachedLine = null;
cachedHints = null;
cachedType = null;
@@ -33,6 +33,10 @@
color: rgb(0, 0, 100); /* blue */
}
.brackets-js-hints.priority-lowest {
color: rgb(0, 0, 0); /* black */
}
.brackets-js-hints.variable-hint {
}
@@ -54,3 +58,9 @@
.brackets-js-hints .matched-hint {
font-weight: bold;
}
.brackets-js-hints.guess-hint {
font-style: italic;
}
@@ -101,24 +101,26 @@ importScripts("thirdparty/requirejs/require.js");
query.file = file;
query.filter = false;
query.sort = false;
query.depths = true;
query.types = true;
var request = {query:query, files:[], offset:offset};
request.files.push({type:"full", name:file, text:text});
return request;
}
var request = buildRequest(dir, file, "completions", offset);
//_log("request " + dir + " " + file + " " + offset + " " + text);
//_log("request " + dir + " " + file + " " + offset /*+ " " + text */);
ternServer.request(request, function(error, data) {
//if (error) return displayError(error);
//_log("completions.length = " + data.completions.length);
var completions = [];
var ternHints = [];
for (var i = 0; i < data.completions.length; ++i) {
var completion = data.completions[i];//, className = typeToIcon(completion.type);
//if (data.guess) className += " Tern-completion-guess";
completions.push({value: completion/*, className: className*/});
completions.push({value: completion.name, type: completion.type, depth: completion.depth, guess: completion.guess /*, className: className*/});
}
// Post a message back to the main thread with the completions