Merge branch 'master' into dangoor/prefer-prefix

Conflicts:
	src/extensions/default/JavaScriptCodeHints/main.js
This commit is contained in:
Kevin Dangoor committed 2013-05-13 14:33:22 -04:00
commit 89ba0925e9
136 files changed
+4206 -1106

No files matched your search

@@ -30,12 +30,13 @@ define(function (require, exports, module) {
var LANGUAGE_ID = "javascript",
SINGLE_QUOTE = "'",
DOUBLE_QUOTE = "\"",
TERN_ADD_FILES_MSG = "AddFiles",
TERN_INIT_MSG = "Init",
TERN_JUMPTODEF_MSG = "JumptoDef",
TERN_COMPLETIONS_MSG = "Completions",
TERN_GET_FILE_MSG = "GetFile",
TERN_GET_PROPERTIES_MSG = "Properties",
TERN_CALLED_FUNC_TYPE_MSG = "FunctionType";
TERN_CALLED_FUNC_TYPE_MSG = "FunctionType",
TERN_PRIME_PUMP_MSG = "PrimePump";
/**
* Create a hint token with name value that occurs at the given list of
@@ -72,10 +73,12 @@ define(function (require, exports, module) {
* @return {boolean} - could the token be hintable?
*/
function hintable(token) {
switch (token.className) {
switch (token.type) {
case "comment":
case "number":
case "regexp":
// exclude variable & param decls
case "def":
return false;
default:
return true;
@@ -184,22 +187,23 @@ define(function (require, exports, module) {
}),
LITERALS = annotateLiterals(LITERAL_TOKENS);
exports.makeToken = makeToken;
exports.hintable = hintable;
exports.hintableKey = hintableKey;
exports.maybeIdentifier = maybeIdentifier;
exports.splitPath = splitPath;
exports.eventName = eventName;
exports.annotateLiterals = annotateLiterals;
exports.KEYWORDS = KEYWORDS;
exports.LITERALS = LITERALS;
exports.LANGUAGE_ID = LANGUAGE_ID;
exports.SINGLE_QUOTE = SINGLE_QUOTE;
exports.DOUBLE_QUOTE = DOUBLE_QUOTE;
exports.TERN_JUMPTODEF_MSG = TERN_JUMPTODEF_MSG;
exports.TERN_COMPLETIONS_MSG = TERN_COMPLETIONS_MSG;
exports.TERN_INIT_MSG = TERN_INIT_MSG;
exports.TERN_GET_FILE_MSG = TERN_GET_FILE_MSG;
exports.TERN_GET_PROPERTIES_MSG = TERN_GET_PROPERTIES_MSG;
exports.makeToken = makeToken;
exports.hintable = hintable;
exports.hintableKey = hintableKey;
exports.maybeIdentifier = maybeIdentifier;
exports.splitPath = splitPath;
exports.eventName = eventName;
exports.annotateLiterals = annotateLiterals;
exports.KEYWORDS = KEYWORDS;
exports.LITERALS = LITERALS;
exports.LANGUAGE_ID = LANGUAGE_ID;
exports.SINGLE_QUOTE = SINGLE_QUOTE;
exports.DOUBLE_QUOTE = DOUBLE_QUOTE;
exports.TERN_ADD_FILES_MSG = TERN_ADD_FILES_MSG;
exports.TERN_JUMPTODEF_MSG = TERN_JUMPTODEF_MSG;
exports.TERN_COMPLETIONS_MSG = TERN_COMPLETIONS_MSG;
exports.TERN_INIT_MSG = TERN_INIT_MSG;
exports.TERN_GET_FILE_MSG = TERN_GET_FILE_MSG;
exports.TERN_CALLED_FUNC_TYPE_MSG = TERN_CALLED_FUNC_TYPE_MSG;
exports.TERN_PRIME_PUMP_MSG = TERN_PRIME_PUMP_MSG;
});
@@ -51,19 +51,30 @@ define(function (require, exports, module) {
rootTernDir = null,
projectRoot = null,
ternPromise = null,
addFilesPromise = null,
resolvedFiles = {}, // file -> resolved file
_ternWorker = (function () {
numInitialFiles = 0,
numResolvedFiles = 0,
numAddedFiles = 0,
stopAddingFiles = false,
_ternWorker = (function () {
var path = ExtensionUtils.getModulePath(module, "tern-worker.js");
return new Worker(path);
}());
var MAX_TEXT_LENGTH = 1000000, // about 1MB
MAX_FILES_IN_DIR = 100;
MAX_FILES_IN_DIR = 100,
MAX_FILES_IN_PROJECT = 100;
/**
* Create a new tern server.
*/
function initTernServer(dir, files) {
numResolvedFiles = 0;
numAddedFiles = 0;
stopAddingFiles = false;
numInitialFiles = files.length;
_ternWorker.postMessage({
type : HintUtils.TERN_INIT_MSG,
dir : dir,
@@ -73,10 +84,40 @@ define(function (require, exports, module) {
rootTernDir = dir + "/";
}
/**
* 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.
if (numResolvedFiles + numAddedFiles < MAX_FILES_IN_PROJECT) {
var available = MAX_FILES_IN_PROJECT - numResolvedFiles - numAddedFiles;
if (available < files.length) {
files = files.slice(0, available);
}
numAddedFiles += files.length;
_ternWorker.postMessage({
type : HintUtils.TERN_ADD_FILES_MSG,
files : files
});
} else {
stopAddingFiles = true;
}
return stopAddingFiles;
}
/**
* An array of library names that contain JavaScript builtins definitions.
*
* @returns {Array} - array of library names.
* @returns {Array.<string>} - array of library names.
*/
function getBuiltins() {
return builtinLibraryNames;
@@ -112,11 +153,199 @@ define(function (require, exports, module) {
* the message will not be posted until initialization is complete
*/
function postMessage(msg) {
addFilesPromise.done(function (ternWorker) {
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) {
ternWorker.postMessage(msg);
});
}
/**
* For each file in a directory get a callback with the path of the javascript
* file or directory.
*
* dotfiles are ignored.
*
* @param {string} dir - directory in which to list the files.
* @param {function()} doneCallback - called after all of the files have
* been listed.
* @param {function(string)} fileCallback - callback for javascript files.
* The function is passed the full path name of the file.
* @param {!function(string)=} directoryCallback - callback for directory
* files. The function is passed the full path name of the file (optional).
* @param {!function(string)=} errorCallback - Callback for errors (optional).
*/
function forEachFileInDirectory(dir, doneCallback, fileCallback, directoryCallback, errorCallback) {
var files = [];
NativeFileSystem.resolveNativeFileSystemPath(dir, function (dirEntry) {
var reader = dirEntry.createReader();
reader.readEntries(function (entries) {
entries.slice(0, MAX_FILES_IN_DIR).forEach(function (entry) {
var path = entry.fullPath,
split = HintUtils.splitPath(path),
file = split.file;
if (fileCallback && entry.isFile) {
if (file.indexOf(".") > 0) { // ignore .dotfiles
var languageID = LanguageManager.getLanguageForPath(path).getId();
if (languageID === HintUtils.LANGUAGE_ID) {
fileCallback(path);
}
}
} else if (directoryCallback && entry.isDirectory) {
var dirName = HintUtils.splitPath(split.dir).file;
if (dirName.indexOf(".") !== 0) { // ignore .dotfiles
directoryCallback(entry.fullPath);
}
}
});
doneCallback();
}, function (err) {
if (errorCallback) {
errorCallback(err);
}
console.log("Unable to refresh directory: " + err);
});
}, function (err) {
if (errorCallback) {
errorCallback(err);
}
console.log("Directory \"%s\" does not exist", dir);
});
}
/**
* Get a list of javascript files in a given directory.
*
* @param {string} dir - directory to list the files of.
* @param {function(Array.<string>)} successCallback - callback with
* array of file path names.
*/
function getFilesInDirectory(dir, successCallback) {
var files = []; // file names without paths.
/**
* Call the success callback with all of the found files.
*/
function doneCallback() {
successCallback(files);
}
/**
* Add files to global list.
*
* @param path - full path of file.
*/
function fileCallback(path) {
files.push(path);
}
forEachFileInDirectory(dir, doneCallback, fileCallback);
}
/**
* Add the files in the directory and subdirectories of a given directory
* to tern.
*
* @param {string} dir - the directory to add
* be included.
* @param {function ()} doneCallback - called when all files have been
* added to tern.
*/
function addAllFilesAndSubdirectories(dir, doneCallback) {
var numDirectoriesLeft = 1, // number of directories to process
excludedFilesString = "require\\.js$|jquery-[\\d]\\.[\\d]\\.js$|\\.min\\.js$",
excludedFilesRegEx = new RegExp(excludedFilesString);
/**
* Add the files in the directory and subdirectories of a given directory
* to tern, excluding the rootTernDir).
*
* @param {string} dir - the directory to add
* be included.
* @param {function()} successCallback - callback when
* done processing files.
*/
function addAllFilesRecursively(dir, successCallback) {
var files = [],
dirs = [];
function doneCallback() {
numDirectoriesLeft--;
if (!stopAddingFiles && files.length > 0 &&
(dir + "/") !== rootTernDir) {
addFilesToTern(files);
}
if (!stopAddingFiles) {
dirs.forEach(function (path) {
var dir = HintUtils.splitPath(path).dir;
if (!stopAddingFiles) {
numDirectoriesLeft++;
addAllFilesRecursively(dir, successCallback);
}
});
}
if (numDirectoriesLeft === 0) {
successCallback();
}
}
/**
* Add files to global list.
*
* @param path - full path of file.
*/
function fileCallback(path) {
if (!excludedFilesRegEx.test(path)) {
files.push(path);
}
}
/**
* For each directory, add all the files in its subdirectory.
*
* @param path
*/
function directoryCallback(path) {
if (path !== rootTernDir) {
dirs.push(path);
}
}
forEachFileInDirectory(dir, doneCallback, fileCallback, directoryCallback);
}
addAllFilesRecursively(dir, function () {
doneCallback();
});
}
/**
* Determine whether the current set of files are using modules to pull in
* additional files.
*
* @returns {boolean} - true if more files than the current directory have
* been read in.
*/
function usingModules() {
return numInitialFiles !== numResolvedFiles;
}
/**
* Get a Promise for the definition from TernJS, for the file & offset passed in.
@@ -152,7 +381,7 @@ define(function (require, exports, module) {
dir = split.dir,
file = split.file;
var ternPromise = getJumptoDef(dir, file, offset, document.getText());
var ternPromise = getJumptoDef(dir, path, offset, session.getJavascriptText());
return {promise: ternPromise};
}
@@ -208,43 +437,24 @@ define(function (require, exports, module) {
* @param {string} file - the name of the file
* @param {number} offset - the offset in the file the hints should be calculate at
* @param {string} text - the text of the file
* @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(dir, file, offset, text) {
function getTernHints(dir, file, offset, text, isProperty) {
postMessage({
type: HintUtils.TERN_COMPLETIONS_MSG,
dir: dir,
file: file,
offset: offset,
text: text
text: text,
isProperty: isProperty
});
return addPendingRequest(file, offset, HintUtils.TERN_COMPLETIONS_MSG);
}
/**
* 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 {string} dir - the directory the file is in
* @param {string} file - the name of the file
* @param {number} offset - the offset in the file the hints should be calculate at
* @param {string} text - the text of the file
* @return {jQuery.Promise} - a promise that will resolve to an array of properties when
* it is done
*/
function getTernProperties(dir, file, offset, text) {
postMessage({
type: HintUtils.TERN_GET_PROPERTIES_MSG,
dir: dir,
file: file,
offset: offset,
text: text
});
return addPendingRequest(file, offset, HintUtils.TERN_GET_PROPERTIES_MSG);
}
/**
* Get a Promise for the function type from TernJS.
* @param {string} dir - the directory the file is in
@@ -286,7 +496,7 @@ define(function (require, exports, module) {
* @return {jQuery.Promise} - The promise will not complete until the tern
* hints have completed.
*/
function requestHints(session, document, offset) {
function requestHints(session, document) {
var path = document.file.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
@@ -295,32 +505,25 @@ define(function (require, exports, module) {
var $deferredHints = $.Deferred(),
hintPromise,
fnTypePromise,
propsPromise;
hintPromise = getTernHints(dir, file, offset, document.getText());
text = session.getJavascriptText(),
offset = session.getOffset();
var sessionType = session.getType();
if (sessionType.property) {
propsPromise = getTernProperties(dir, file, offset, document.getText());
} else {
var $propsDeferred = $.Deferred();
propsPromise = $propsDeferred.promise();
$propsDeferred.resolveWith(null);
}
hintPromise = getTernHints(dir, path, offset, text, sessionType.property);
if (sessionType.showFunctionType) {
// Show function sig
fnTypePromise = getTernFunctionType(dir, file, sessionType.functionCallPos, offset, document.getText());
fnTypePromise = getTernFunctionType(dir, path, sessionType.functionCallPos, offset, text);
} else {
var $fnTypeDeferred = $.Deferred();
fnTypePromise = $fnTypeDeferred.promise();
$fnTypeDeferred.resolveWith(null);
}
$.when(hintPromise, fnTypePromise, propsPromise).done(
function (completions, fnType, properties) {
$.when(hintPromise, fnTypePromise).done(
function (completions, fnType) {
session.setTernHints(completions);
session.setFnType(fnType);
session.setTernProperties(properties);
$deferredHints.resolveWith(null);
}
);
@@ -357,7 +560,7 @@ define(function (require, exports, module) {
* @param {{dir:string, file:string, offset:number, completions:Array.<string>}} response - the response from the worker
*/
function handleTernCompletions(response) {
var file = response.file,
offset = response.offset,
completions = response.completions,
@@ -376,7 +579,7 @@ define(function (require, exports, module) {
}
}
}
/**
* @param {string} file a relative path
* @return {string} returns the path we resolved when we tried to parse the file, or undefined
@@ -394,7 +597,7 @@ define(function (require, exports, module) {
function handleTernGetFile(request) {
function replyWith(name, txt) {
postMessage({
_postMessageByPass({
type: HintUtils.TERN_GET_FILE_MSG,
file: name,
text: txt
@@ -402,7 +605,7 @@ define(function (require, exports, module) {
}
var name = request.file;
/**
* Helper function to get the text of a given document and send it to tern.
* If we successfully get the document from the DocumentManager then the text of
@@ -416,6 +619,7 @@ define(function (require, exports, module) {
function getDocText(filePath) {
return DocumentManager.getDocumentForPath(filePath).done(function (document) {
resolvedFiles[name] = filePath;
numResolvedFiles++;
replyWith(name, document.getText());
});
}
@@ -453,63 +657,132 @@ define(function (require, exports, module) {
replyWith(name, "");
});
}
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);
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
* @param {string} text - text of file
* @return {jQuery.Promise} - the promise for the request
*/
function primePump(path, text) {
_postMessageByPass({
type : HintUtils.TERN_PRIME_PUMP_MSG,
path : path,
text : text
});
return addPendingRequest(path, 0, HintUtils.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, 0, type);
if ($deferredHints) {
$deferredHints.resolve();
}
}
/**
* We can skip tern initialization if we are opening a file that has
* already been added to tern.
*
* @param {string} newFile - full path of new file being opened in the editor.
* @returns {boolean} - true if tern initialization should be skipped,
* false otherwise.
*/
function canSkipTernInitialization(newFile) {
return resolvedFiles[newFile] !== undefined;
}
/**
* Called each time a new editor becomes active. Refreshes the outer scopes
* of the given file as well as of the other files in the given directory.
*
*
* @param {Session} session - the active hinting session
* @param {Document} document - the document of the editor that has changed
* @param {boolean} shouldPrimePump - true if the pump should be primed.
*/
function handleEditorChange(document) {
function handleEditorChange(session, document, shouldPrimePump) {
var path = document.file.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
files = [],
file = split.file;
file = split.file,
pr;
pr = ProjectManager.getProjectRoot() ? ProjectManager.getProjectRoot().fullPath : null;
// avoid re-initializing tern if possible.
if (canSkipTernInitialization(path)) {
// skipping initializing tern
return;
}
var ternDeferred = $.Deferred(),
addFilesDeferred = $.Deferred();
var ternDeferred = $.Deferred();
ternPromise = ternDeferred.promise();
addFilesPromise = addFilesDeferred.promise();
pendingTernRequests = [];
resolvedFiles = {};
projectRoot = ProjectManager.getProjectRoot() ? ProjectManager.getProjectRoot().fullPath : null;
NativeFileSystem.resolveNativeFileSystemPath(dir, function (dirEntry) {
var reader = dirEntry.createReader();
projectRoot = pr;
getFilesInDirectory(dir, function (files) {
initTernServer(dir, files);
ternDeferred.resolveWith(null, [_ternWorker]);
reader.readEntries(function (entries) {
entries.slice(0, MAX_FILES_IN_DIR).forEach(function (entry) {
if (entry.isFile) {
var path = entry.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
file = split.file;
if (file.indexOf(".") > 1) { // ignore /.dotfiles
var languageID = LanguageManager.getLanguageForPath(entry.fullPath).getId();
if (languageID === HintUtils.LANGUAGE_ID) {
files.push(file);
if (shouldPrimePump) {
var hintsPromise = primePump(path, document.getText());
hintsPromise.done(function () {
if (!usingModules()) {
// Read the subdirectories of the new file's directory.
// Read them first in case there are too many files to
// read in the project.
addAllFilesAndSubdirectories(dir, function () {
// If the file is in the project root, then read
// all the files under the project root.
if (projectRoot && (dir + "/").indexOf(projectRoot) === 0) {
addAllFilesAndSubdirectories(projectRoot, function () {
// prime the pump again but this time don't wait
// for completion.
primePump(path, document.getText());
addFilesDeferred.resolveWith(null, [_ternWorker]);
});
} else {
addFilesDeferred.resolveWith(null, [_ternWorker]);
}
}
});
} else {
addFilesDeferred.resolveWith(null, [_ternWorker]);
}
});
initTernServer(dir, files);
ternDeferred.resolveWith(null, [_ternWorker]);
}, function (err) {
console.log("Unable to refresh directory: " + err);
});
}, function (err) {
console.log("Directory \"%s\" does not exist", dir);
} else {
addFilesDeferred.resolveWith(null, [_ternWorker]);
}
});
}
/*
@@ -526,8 +799,7 @@ define(function (require, exports, module) {
type = response.type;
if (type === HintUtils.TERN_COMPLETIONS_MSG ||
type === HintUtils.TERN_CALLED_FUNC_TYPE_MSG ||
type === HintUtils.TERN_GET_PROPERTIES_MSG) {
type === HintUtils.TERN_CALLED_FUNC_TYPE_MSG) {
// handle any completions the worker calculated
handleTernCompletions(response);
} else if (type === HintUtils.TERN_GET_FILE_MSG) {
@@ -535,16 +807,18 @@ define(function (require, exports, module) {
handleTernGetFile(response);
} else if (type === HintUtils.TERN_JUMPTODEF_MSG) {
handleJumptoDef(response);
} else if (type === HintUtils.TERN_PRIME_PUMP_MSG) {
handlePrimePumpCompletion(response);
} else {
console.log("Worker: " + (response.log || response));
}
});
exports.getBuiltins = getBuiltins;
exports.getResolvedPath = getResolvedPath;
exports.getTernHints = getTernHints;
exports.handleEditorChange = handleEditorChange;
exports.handleFileChange = handleFileChange;
exports.requestJumptoDef = requestJumptoDef;
exports.requestHints = requestHints;
exports.getTernHints = getTernHints;
exports.getResolvedPath = getResolvedPath;
exports.requestJumptoDef = requestJumptoDef;
});
@@ -21,13 +21,16 @@
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define, brackets, $ */
define(function (require, exports, module) {
"use strict";
var StringMatch = brackets.getModule("utils/StringMatch"),
LanguageManager = brackets.getModule("language/LanguageManager"),
HTMLUtils = brackets.getModule("language/HTMLUtils"),
TokenUtils = brackets.getModule("utils/TokenUtils"),
HintUtils = require("HintUtils"),
ScopeManager = require("ScopeManager");
@@ -42,12 +45,25 @@ define(function (require, exports, module) {
this.editor = editor;
this.path = editor.document.file.fullPath;
this.ternHints = [];
this.ternProperties = [];
this.fnType = null;
this.builtins = ScopeManager.getBuiltins();
this.builtins.push("requirejs.js"); // consider these globals as well.
this.builtins = null;
}
/**
* Get the builtin libraries tern is using.
*
* @returns {Array.<string>} - array of library names.
* @private
*/
Session.prototype._getBuiltins = function () {
if (!this.builtins) {
this.builtins = ScopeManager.getBuiltins();
this.builtins.push("requirejs.js"); // consider these globals as well.
}
return this.builtins;
};
/**
* Get the name of the file associated with the current session
*
@@ -107,7 +123,24 @@ define(function (require, exports, module) {
return cm.getTokenAt(this.getCursor());
}
};
/**
* Get the token after the one at the given cursor position
*
* @param {{line: number, ch: number}} cursor - cursor position before
* which a token should be retrieved
* @return {Object} - the CodeMirror token after the one at the given
* cursor position
*/
Session.prototype.getNextTokenOnLine = function (cursor) {
cursor = this.getNextCursorOnLine(cursor);
if (cursor) {
return this.getToken(cursor);
}
return null;
};
/**
* Get the next cursor position on the line, or null if there isn't one.
*
@@ -115,9 +148,8 @@ define(function (require, exports, module) {
* immediately following the current cursor position, or null if
* none exists.
*/
Session.prototype.getNextCursorOnLine = function () {
var cursor = this.getCursor(),
doc = this.editor.document,
Session.prototype.getNextCursorOnLine = function (cursor) {
var doc = this.editor.document,
line = doc.getLine(cursor.line);
if (cursor.ch < line.length) {
@@ -216,6 +248,28 @@ define(function (require, exports, module) {
}
};
/**
* @return {{line:number, ch:number}} - the line, col info for where the previous "."
* in a property lookup occurred, or undefined if no previous "." was found.
*/
Session.prototype.findPreviousDot = function () {
var cursor = this.getCursor(),
token = this.getToken(cursor);
// If the cursor is right after the dot, then the current token will be "."
if (token && token.string === ".") {
return cursor;
} else {
// If something has been typed like 'foo.b' then we have to look back 2 tokens
// to get past the 'b' token
token = this._getPreviousToken(cursor);
if (token && token.string === ".") {
return cursor;
}
}
return undefined;
};
/**
* Get the type of the current session, i.e., whether it is a property
* lookup and, if so, what the context of the lookup is.
@@ -235,18 +289,30 @@ define(function (require, exports, module) {
* function being called
*/
Session.prototype.getType = function () {
function getLexicalState(token) {
if (token.state.lexical) {
// in a javascript file this is just in the state field
return token.state.lexical;
} else if (token.state.localState && token.state.localState.lexical) {
// inline javascript in an html file will have this in
// the localState field
return token.state.localState.lexical;
}
}
var propertyLookup = false,
inFunctionCall = false,
showFunctionType = false,
context = null,
cursor = this.getCursor(),
functionCallPos,
token = this.getToken(cursor);
token = this.getToken(cursor),
lexical;
if (token) {
// if this token is part of a function call, then the tokens lexical info
// will be annotated with "call"
if (token.state.lexical.info === "call") {
lexical = getLexicalState(token);
if (lexical.info === "call") {
inFunctionCall = true;
if (this.getQuery().length > 0) {
inFunctionCall = false;
@@ -263,7 +329,7 @@ define(function (require, exports, module) {
// and it will prevent us from walking back thousands of lines if something went wrong.
// there is nothing magical about 9 lines, and it can be adjusted if it doesn't seem to be
// working well
var col = token.state.lexical.column,
var col = lexical.column,
line,
e,
found;
@@ -278,19 +344,14 @@ define(function (require, exports, module) {
}
}
}
if (token.string === ".") {
if (token.type === "property") {
propertyLookup = true;
}
cursor = this.findPreviousDot();
if (cursor) {
propertyLookup = true;
context = this.getContext(cursor);
} else {
if (token.className === "property") {
propertyLookup = true;
}
token = this._getPreviousToken(cursor);
if (token && token.string === ".") {
propertyLookup = true;
context = this.getContext(cursor);
}
}
if (propertyLookup) { showFunctionType = false; }
}
@@ -321,7 +382,7 @@ define(function (require, exports, module) {
var MAX_DISPLAYED_HINTS = 500,
type = this.getType(),
builtins = this.builtins,
builtins = this._getBuiltins(),
hints;
/**
@@ -379,12 +440,6 @@ define(function (require, exports, module) {
if (type.property) {
hints = this.ternHints || [];
hints = filterWithQueryAndMatcher(hints, matcher);
// If there are no hints then switch over to guesses.
if (hints.length === 0) {
hints = filterWithQueryAndMatcher(this.ternProperties, matcher);
}
StringMatch.multiFieldSort(hints, { matchGoodness: 0, value: 1 });
} else if (type.showFunctionType) {
hints = this.getFunctionTypeHint();
@@ -399,15 +454,14 @@ define(function (require, exports, module) {
if (hints.length > MAX_DISPLAYED_HINTS) {
hints = hints.slice(0, MAX_DISPLAYED_HINTS);
}
return hints;
};
Session.prototype.setTernHints = function (newHints) {
this.ternHints = newHints;
};
Session.prototype.setTernProperties = function (newProperties) {
this.ternProperties = newProperties;
};
Session.prototype.setFnType = function (newFnType) {
this.fnType = newFnType;
};
@@ -425,7 +479,12 @@ define(function (require, exports, module) {
cursor = sessionType.functionCallPos,
token = cursor ? this.getToken(cursor) : undefined,
varName;
if (token) {
if (token &&
// only change the 'fn' when the token looks like a function
// name, and isn't some other kind of expression
(token.type === "variable" ||
token.type === "variable-2" ||
token.type === "property")) {
varName = token.string;
if (varName) {
fnHint = varName + fnHint.substr(2);
@@ -435,6 +494,67 @@ define(function (require, exports, module) {
}
return hints;
};
/**
* Get the javascript text of the file open in the editor for this Session.
* For a javascript file, this is just the text of the file. For an HTML file,
* this will be only the text in the <script> tags. This is so that we can pass
* just the javascript text to tern, and avoid confusing it with HTML tags, since it
* only knows how to parse javascript.
* @return {string} - the "javascript" text that can be sent to Tern.
*/
Session.prototype.getJavascriptText = function () {
if (LanguageManager.getLanguageForPath(this.editor.document.file.fullPath).getId() === "html") {
// HTML file - need to send back only the bodies of the
// <script> tags
var text = "",
offset = this.getOffset(),
cursor = this.getCursor(),
editor = this.editor,
scriptBlocks = HTMLUtils.findBlocks(editor, "javascript");
// Add all the javascript text
// For non-javascript blocks we replace everything except for newlines
// with whitespace. This is so that the offset and cursor positions
// we get from the document still work.
// Alternatively we could strip the non-javascript text, and modify the offset,
// and/or cursor, but then we have to remember how to reverse the translation
// to support jump-to-definition
var htmlStart = {line: 0, ch: 0};
scriptBlocks.forEach(function (scriptBlock) {
var start = scriptBlock.start,
end = scriptBlock.end;
// get the preceding html text, and replace it with whitespace
var htmlText = editor.document.getRange(htmlStart, start);
htmlText = htmlText.replace(/./g, " ");
htmlStart = end;
text += htmlText + scriptBlock.text;
});
return text;
} else {
// Javascript file, just return the text
return this.editor.document.getText();
}
};
/**
* Deterimine if the cursor is located in the name of a function declaration.
* This is so we can suppress hints when in a funtion name, as we do for variable and
* parameter declarations, but we can tell those from the token itself rather than having
* to look at previous tokens.
*
* @return {boolean} - true if the current cursor position is in the name of a function decl.
*/
Session.prototype.isFunctionName = function () {
var cursor = this.getCursor(),
token = this.getToken(cursor),
prevToken = this._getPreviousToken(cursor);
return prevToken.string === "function";
};
module.exports = Session;
});
@@ -38,19 +38,31 @@ define(function (require, exports, module) {
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
StringUtils = brackets.getModule("utils/StringUtils"),
StringMatch = brackets.getModule("utils/StringMatch"),
LanguageManager = brackets.getModule("language/LanguageManager"),
HintUtils = require("HintUtils"),
ScopeManager = require("ScopeManager"),
Session = require("Session");
Session = require("Session"),
Acorn = require("thirdparty/acorn/acorn");
var KeyboardPrefs = JSON.parse(require("text!keyboard.json"));
var JUMPTO_DEFINITION = "navigate.jumptoDefinition";
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
cachedLine = null, // the line number for the cached scope
matcher = null; // string matcher for hints
var session = null, // object that encapsulates the current session state
cachedCursor = null, // last cursor of the current hinting session
cachedHints = null, // sorted hints for the current hinting session
cachedType = null, // describes the lookup type and the object context
cachedToken = null, // the token used in the current hinting session
matcher = null; // string matcher for hints
/**
* Get the value of current session.
* Used for unit testing.
* @returns {Session} - the current session.
*/
function getSession() {
return session;
}
/**
* Creates a hint response object. Filters the hint list using the query
@@ -82,7 +94,7 @@ define(function (require, exports, module) {
var $hintObj = $("<span>").addClass("brackets-js-hints");
// level indicates either variable scope or property confidence
if (!type.property && token.depth !== undefined) {
if (!type.property && !token.builtin && token.depth !== undefined) {
switch (token.depth) {
case 0:
$hintObj.addClass("priority-high");
@@ -173,14 +185,69 @@ define(function (require, exports, module) {
JSHints.prototype.needNewHints = function (session) {
var cursor = session.getCursor(),
type = session.getType();
return !cachedHints ||
cachedLine !== cursor.line ||
cachedCursor.line !== cursor.line ||
type.property !== cachedType.property ||
type.context !== cachedType.context ||
type.showFunctionType !== cachedType.showFunctionType;
};
/**
* Have conditions have changed enough to justify closing the hints popup?
*
* @param {Session} session - the active hinting session
* @return {boolean} - true if the hints popup should be closed.
*/
JSHints.prototype.shouldCloseHints = function (session) {
// close if the token className has changed then close the hints.
var cursor = session.getCursor(),
token = session.getToken(cursor),
lastToken = cachedToken;
// if the line has changed, then close the hints
if (!cachedCursor || cursor.line !== cachedCursor.line) {
return true;
}
if (token.type === null) {
token = session.getNextTokenOnLine(cursor);
}
if (lastToken && lastToken.type === null) {
lastToken = session.getNextTokenOnLine(cachedCursor);
}
// Both of the tokens should never be null (happens when token is off
// the end of the line), so one is null then close the hints.
if (!lastToken || !token ||
token.type !== lastToken.type) {
return true;
}
// Test if one token string is a prefix of the other.
// If one is a prefix of the other then consider it the
// same token and don't close the hints.
if (token.string.length >= lastToken.string.length) {
return token.string.indexOf(lastToken.string) !== 0;
} else {
return lastToken.string.indexOf(token.string) !== 0;
}
};
/**
* @return {boolean} - true if the document is a html file
*/
function isHTMLFile(document) {
var languageID = LanguageManager.getLanguageForPath(document.file.fullPath).getId();
return languageID === "html";
}
function isInlineScript(editor) {
return editor.getModeForSelection() === "javascript";
}
/**
* Determine whether hints are available for a given editor context
*
@@ -190,19 +257,28 @@ define(function (require, exports, module) {
*/
JSHints.prototype.hasHints = function (editor, key) {
if (session && HintUtils.hintableKey(key)) {
if (isHTMLFile(session.editor.document)) {
if (!isInlineScript(session.editor)) {
return false;
}
}
var cursor = session.getCursor(),
token = session.getToken(cursor);
// don't autocomplete within strings or comments, etc.
if (token && HintUtils.hintable(token)) {
if (session.isFunctionName()) {
return false;
}
var offset = session.getOffset(),
type = session.getType(),
query = session.getQuery();
if (this.needNewHints(session)) {
//console.log("clear hints");
cachedLine = null;
cachedCursor = null;
cachedHints = null;
cachedToken = null;
matcher = null;
}
return true;
@@ -226,16 +302,23 @@ define(function (require, exports, module) {
var type = session.getType(),
query = session.getQuery();
// If the hint context is changed and the hints are open, then
// close the hints by returning null;
if (CodeHintManager.isOpen() && this.shouldCloseHints(session)) {
return null;
}
cachedCursor = cursor;
cachedToken = token;
// Compute fresh hints if none exist, or if the session
// type has changed since the last hint computation
if (this.needNewHints(session)) {
var offset = session.getOffset(),
scopeResponse = ScopeManager.requestHints(session, session.editor.document, offset);
var scopeResponse = ScopeManager.requestHints(session, session.editor.document);
if (scopeResponse.hasOwnProperty("promise")) {
var $deferredHints = $.Deferred();
scopeResponse.promise.done(function () {
cachedLine = cursor.line;
cachedType = session.getType();
matcher = new StringMatch.StringMatcher({
preferPrefixMatches: true
@@ -255,8 +338,6 @@ define(function (require, exports, module) {
});
return $deferredHints;
} else {
cachedLine = cursor.line;
}
}
@@ -272,7 +353,7 @@ define(function (require, exports, module) {
/**
* Inserts the hint selected by the user into the current editor.
*
* @param {jQuery.Object} hint - hint object to insert into current editor
* @param {jQuery.Object} $hintObj - hint object to insert into current editor
* @return {boolean} - should a new hinting session be requested
* immediately after insertion?
*/
@@ -287,8 +368,7 @@ define(function (require, exports, module) {
delimiter;
if (token && token.string === ".") {
var nextCursor = session.getNextCursorOnLine(),
nextToken = nextCursor ? session.getToken(nextCursor) : null;
var nextToken = session.getNextTokenOnLine(cursor);
if (nextToken && // don't replace delimiters, etc.
HintUtils.maybeIdentifier(nextToken.string) &&
@@ -318,15 +398,52 @@ define(function (require, exports, module) {
// if we were displaying a function type
return false;
}
if (session.getType().property) {
// if we're inserting a property name, we need to make sure the
// hint is a valid property name.
// to check this, run the hint through Acorns tokenizer
// it should result in one token, and that token should either be
// a 'name' or a 'keyword', as javascript allows keywords as property names
var tokenizer = Acorn.tokenize(completion);
var currentToken = tokenizer(),
invalidPropertyName = false;
// the name is invalid if the hint is not a 'name' or 'keyword' token
if (currentToken.type !== Acorn.tokTypes.name && !currentToken.type.keyword) {
invalidPropertyName = true;
} else {
// check for a second token - if there is one (other than 'eof')
// then the hint isn't a valid property name either
currentToken = tokenizer();
if (currentToken.type !== Acorn.tokTypes.eof) {
invalidPropertyName = true;
}
}
if (invalidPropertyName) {
// need to walk back to the '.' and replace
// with '["<hint>"]
var dotCursor = session.findPreviousDot();
if (dotCursor) {
completion = "[\"" + completion + "\"]";
start.line = dotCursor.line;
start.ch = dotCursor.ch - 1;
}
}
}
// Replace the current token with the completion
session.editor.document.replaceRange(completion, start, end);
// HACK (tracking adobe/brackets#1688): We talk to the private CodeMirror instance
// directly to replace the range instead of using the Document, as we should. The
// reason is due to a flaw in our current document synchronization architecture when
// inline editors are open.
session.editor._codeMirror.replaceRange(completion, start, end);
// Return false to indicate that another hinting session is not needed
return false;
};
// load the extension
// load the extension
AppInit.appReady(function () {
/*
@@ -334,10 +451,11 @@ define(function (require, exports, module) {
* information, and reject any pending deferred requests.
*
* @param {Editor} editor - editor context to be initialized.
* @param {boolean} primePump - true if the pump should be primed.
*/
function initializeSession(editor) {
ScopeManager.handleEditorChange(editor.document);
function initializeSession(editor, primePump) {
session = new Session(editor);
ScopeManager.handleEditorChange(session, editor.document, primePump);
cachedHints = null;
}
@@ -349,12 +467,12 @@ define(function (require, exports, module) {
*/
function installEditorListeners(editor) {
// always clean up cached scope and hint info
cachedLine = null;
cachedCursor = null;
cachedHints = null;
cachedType = null;
if (editor && editor.getLanguageForSelection().getId() === HintUtils.LANGUAGE_ID) {
initializeSession(editor);
initializeSession(editor, true);
$(editor)
.on(HintUtils.eventName("change"), function () {
ScopeManager.handleFileChange(editor.document);
@@ -425,7 +543,7 @@ define(function (require, exports, module) {
// Add the menu item
var menu = Menus.getMenu(Menus.AppMenuBar.NAVIGATE_MENU);
if (menu) {
menu.addMenuItem(JUMPTO_DEFINITION, KeyboardPrefs.jumptoDefinition, Menus.BEFORE, Commands.NAVIGATE_GOTO_DEFINITION);
menu.addMenuItem(JUMPTO_DEFINITION, KeyboardPrefs.jumptoDefinition, Menus.AFTER, Commands.NAVIGATE_GOTO_DEFINITION);
}
ExtensionUtils.loadStyleSheet(module, "styles/brackets-js-hints.css");
@@ -439,9 +557,10 @@ define(function (require, exports, module) {
installEditorListeners(EditorManager.getActiveEditor());
var jsHints = new JSHints();
CodeHintManager.registerHintProvider(jsHints, [HintUtils.LANGUAGE_ID], 0);
CodeHintManager.registerHintProvider(jsHints, [HintUtils.LANGUAGE_ID, "html"], 0);
// for unit testing
exports.getSession = getSession;
exports.jsHintProvider = jsHints;
exports.initializeSession = initializeSession;
exports.handleJumpToDefinition = handleJumpToDefinition;
@@ -115,7 +115,7 @@ importScripts("thirdparty/requirejs/require.js");
query.depths = true;
query.guess = true;
query.origins = true;
query.expandWordForward = true;
query.expandWordForward = false;
var request = {query: query, files: [], offset: offset};
request.files.push({type: "full", name: file, text: text});
@@ -160,51 +160,16 @@ importScripts("thirdparty/requirejs/require.js");
});
});
}
/**
* Get the completions for the given offset
* @param {string} dir - the directory
* @param {string} file - the file name
* @param {number} offset - the offset into the file where we want completions for
* @param {string} text - the text of the file
*/
function getTernHints(dir, file, offset, text) {
var request = buildRequest(dir, file, "completions", offset, text),
i;
//_log("request " + dir + " " + file + " " + offset /*+ " " + text */);
ternServer.request(request, function (error, data) {
var completions = [];
if (error) {
_log("Error returned from Tern 'completions' request: " + error);
} else {
//_log("found " + data.completions.length + " for " + file + "@" + offset);
for (i = 0; i < data.completions.length; ++i) {
var completion = data.completions[i];
completions.push({value: completion.name, type: completion.type, depth: completion.depth,
guess: completion.guess, origin: completion.origin});
}
}
// Post a message back to the main thread with the completions
self.postMessage({type: HintUtils.TERN_COMPLETIONS_MSG,
dir: dir,
file: file,
offset: offset,
completions: completions
});
});
}
/**
* Get all the known properties for guessing.
*
* @param {string} dir - the directory
* @param {string} file - the file name
* @param {number} offset - the offset into the file where we want completions for
* @param {string} text - the text of the file
*/
function handleGetProperties(dir, file, offset, text) {
function getTernProperties(dir, file, offset, text) {
var request = buildRequest(dir, file, "properties", undefined, text),
i;
@@ -222,7 +187,7 @@ importScripts("thirdparty/requirejs/require.js");
}
// Post a message back to the main thread with the completions
self.postMessage({type: HintUtils.TERN_GET_PROPERTIES_MSG,
self.postMessage({type: HintUtils.TERN_COMPLETIONS_MSG,
dir: dir,
file: file,
offset: offset,
@@ -230,6 +195,49 @@ importScripts("thirdparty/requirejs/require.js");
});
});
}
/**
* Get the completions for the given offset
* @param {string} dir - the directory
* @param {string} file - the file name
* @param {number} offset - the offset into the file where we want completions for
* @param {string} text - the text of the file
* @param {boolean} isProperty - true if getting a property hint,
* otherwise getting an identifier hint.
*/
function getTernHints(dir, file, offset, text, isProperty) {
var request = buildRequest(dir, file, "completions", offset, text),
i;
//_log("request " + dir + " " + file + " " + offset /*+ " " + text */);
ternServer.request(request, function (error, data) {
var completions = [];
if (error) {
_log("Error returned from Tern 'completions' request: " + error);
} else {
//_log("found " + data.completions.length + " for " + file + "@" + offset);
for (i = 0; i < data.completions.length; ++i) {
var completion = data.completions[i];
completions.push({value: completion.name, type: completion.type, depth: completion.depth,
guess: completion.guess, origin: completion.origin});
}
}
if (completions.length > 0 || !isProperty) {
// Post a message back to the main thread with the completions
self.postMessage({type: HintUtils.TERN_COMPLETIONS_MSG,
dir: dir,
file: file,
offset: offset,
completions: completions
});
} else {
// if there are no completions, then get all the properties
getTernProperties(dir, file, offset, text);
}
});
}
/**
* Get the function type for the given offset
@@ -262,6 +270,35 @@ importScripts("thirdparty/requirejs/require.js");
});
});
}
/**
* Add an array of files to tern.
*
* @param {Array.<string>} files - each string in the array is the full
* path of a file.
*/
function handleAddFiles(files) {
files.forEach(function (file) {
ternServer.addFile(file);
});
}
/**
* Make a completions request to tern to force tern to resolve files
* and create a fast first lookup for the user.
* @param {string} path - the path of the file
* @param {string} text - the text of the file
*/
function handlePrimePump(path, text) {
var request = buildRequest("", path, "completions", 0, text);
ternServer.request(request, function (error, data) {
// Post a message back to the main thread
self.postMessage({type: HintUtils.TERN_PRIME_PUMP_MSG,
path: path
});
});
}
self.addEventListener("message", function (e) {
var dir, file, text, offset,
@@ -274,19 +311,12 @@ importScripts("thirdparty/requirejs/require.js");
var env = request.env,
files = request.files;
initTernServer(env, dir, files);
} else if (type === HintUtils.TERN_COMPLETIONS_MSG) {
dir = request.dir;
file = request.file;
text = request.text;
offset = request.offset;
getTernHints(dir, file, offset, text);
} else if (type === HintUtils.TERN_GET_PROPERTIES_MSG) {
file = request.file;
dir = request.dir;
text = request.text;
offset = request.offset;
handleGetProperties(dir, file, offset, text);
getTernHints(dir, file, offset, text, request.isProperty);
} else if (type === HintUtils.TERN_GET_FILE_MSG) {
file = request.file;
text = request.text;
@@ -304,6 +334,10 @@ importScripts("thirdparty/requirejs/require.js");
text = request.text;
offset = request.offset;
getJumptoDef(dir, file, offset, text);
} else if (type === HintUtils.TERN_ADD_FILES_MSG) {
handleAddFiles(request.files);
} else if (type === HintUtils.TERN_PRIME_PUMP_MSG) {
handlePrimePump(request.path, request.text);
} else {
_log("Unknown message: " + JSON.stringify(request));
}
@@ -1,45 +0,0 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global brackets, require */
var A1 = { propA : 1 },
A2 = { propA : 2 },
A3 = A2;
function funB(paramB1, paramB2) {
'use strict';
var B1 = { propB : 1 },
B2 = { propB : 2 };
function funC(paramC1, paramC2) {
var C1 = { propC : 1 },
C2 = { propC : 2 };
B1.propB = 0;
C1.propC = 0;
B1.foo = 0;
console.log("hello\\\" world!");
}
var s = "a string";
var r = s;
var t = r;
}
/**
* @param {string} a
* @param {number} b
*/
function funD(a, b) {
"use strict";
return {x: a, y: b};
}
require(["MyModule"], function (myModule) {
'use strict';
var x = myModule.a;
});
funB();
var x = A1;
@@ -0,0 +1,145 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global brackets, require */
var A1 = { propA : 1 },
A2 = { propA : 2 },
A3 = A2;
function funB(paramB1, paramB2) {
'use strict';
var B1 = { propB : 1 },
B2 = { propB : 2 };
function funC(paramC1, paramC2) {
var C1 = { propC : 1 },
C2 = { propC : 2 };
B1.propB = 0;
C1.propC = 0;
B1.foo = 0;
console.log("hello\\\" world!");
}
var s = "a string";
var r = s;
var t = r;
}
/**
* @param {string} a
* @param {number} b
*/
function funD(a, b) {
"use strict";
return {x: a, y: b};
}
require(["MyModule"], function (myModule) {
'use strict';
var x = myModule.a;
});
funB();
var x = A1;
var arr = [];
arr["my-key"] = 1;
arr["for"] = 10;
function MClass() {
"use strict";
}
MClass.prototype.calc = function (a4, b4) {
"use strict";
return a4 + b4;
};
var ins1 = new MClass();
ins1.calc(10, 10);
var Person = function (name) {
"use strict";
this.name = name;
};
Person.prototype.getName = function () {
"use strict";
return this.name;
};
var Customer = function (name) {
"use strict";
this.name = name;
};
Customer.prototype = new Person();
var myCustomer = new Customer('Dream Inc.');
myCustomer.getName();
Customer.prototype.setAmountDue = function (amountDue) {
"use strict";
this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function () {
"use strict";
return this.amountDue;
};
function testInnerFunc() {
"use strict";
var t = "test";
function innerFunc(arg) {
return {t: function () {return arg; }};
}
var t2 = innerFunc("test").t().toLocaleLowerCase();
}
/**
* @param {boolean} a
* @param {Date} b
*/
function funTypeAn1(a, b) {
"use strict";
return {x: a, y: b};
}
/**
* @param {function(): number} f
*/
function funFuncArg(f) {
"use strict";
return f();
}
function testRef1() {
"use strict";
return 100;
}
funFuncArg(testRef1); //also test return type
/**
* @param {function(string,number): string} f
*/
function funFunc2Arg(f) {
"use strict";
var s = "test";
return f(s, 10);
}
function testRef2(s, n) {
"use strict";
return s + n;
}
funFunc2Arg(testRef2);
var funArr = [];
funArr.index1 = testRef1;
funArr.index2 = testRef2;
@@ -0,0 +1,35 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test file for codehints in .html file</title>
</head>
<body>
<script src="file1.js"></script>
<script>
var x = "hi";
</script>
some stuff
<input type="button">
<div class="content">
</div>
<script>
function foo(a){
return "hi";
}
</script>
some other stuff
<div class = "content">
</div>
<script>
foo(10);
</script>
</body>
</html>
@@ -0,0 +1,8 @@
var app = app || {};
(function () {
'use strict';
app.a = 1;
}());
@@ -0,0 +1,11 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global */
var app = app || {};
(function () {
'use strict';
app.d = 8;
}());
@@ -0,0 +1,11 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global */
var app = app || {};
(function () {
'use strict';
app.b = 2;
}());
@@ -0,0 +1,11 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global */
var app = app || {};
(function () {
'use strict';
app.b1 = 21;
}());
@@ -0,0 +1,10 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global */
var app = app || {};
(function () {
'use strict';
app.c = 3;
}());
@@ -0,0 +1,11 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global */
var app = app || {};
(function () {
'use strict';
app.d = 4;
}());
@@ -36,7 +36,8 @@ define(function (require, exports, module) {
JSCodeHints = require("main");
var extensionPath = FileUtils.getNativeModuleDirectoryPath(module),
testPath = extensionPath + "/test/file1.js",
testPath = extensionPath + "/unittest-files/basic-test-files/file1.js",
testHtmlPath = extensionPath + "/unittest-files/basic-test-files/index.html",
testDoc = null,
testEditor;
@@ -56,7 +57,7 @@ define(function (require, exports, module) {
// create Editor instance
var editor = new Editor(doc, true, $editorHolder.get(0));
return editor;
}
@@ -76,7 +77,7 @@ define(function (require, exports, module) {
if (key === undefined) {
key = null;
}
expect(provider.hasHints(testEditor, key)).toBe(true);
return provider.getHints(null);
}
@@ -94,7 +95,7 @@ define(function (require, exports, module) {
if (key === undefined) {
key = null;
}
expect(provider.hasHints(testEditor, key)).toBe(false);
}
@@ -141,13 +142,30 @@ define(function (require, exports, module) {
hintList = obj.hints;
});
}
waitsFor(function () {
return complete;
}, "Expected hints did not resolve", 3000);
runs(function () { callback(hintList); });
}
/*
* Test if hints should be closed or not closed at a given position.
*
* @param {Object} provider - a CodeHintProvider object
* @param {Object + jQuery.Deferred} hintObj - a hint response object,
* possibly deferred
* @param {line: number, ch: number} newPos - new position to move to
* after hints are received.
* @param {boolean} expectedValue - true if hints should close,
* false otherwise.
*/
function expectCloseHints(provider, hintObj, newPos, expectedValue) {
_waitForHints(hintObj, function (hintList) {
testEditor.setCursorPos(newPos);
expect(provider.shouldCloseHints(JSCodeHints.getSession())).toBe(expectedValue);
});
}
/*
* Expect a given list of hints to be absent from a given hint
@@ -299,34 +317,41 @@ define(function (require, exports, module) {
});
}
describe("JavaScript Code Hinting", function () {
function setupTest(path, primePump) {
DocumentManager.getDocumentForPath(path).done(function (doc) {
testDoc = doc;
});
waitsFor(function () {
return testDoc !== null;
}, "Unable to open test document", 10000);
// create Editor instance (containing a CodeMirror instance)
runs(function () {
testEditor = createMockEditor(testDoc);
JSCodeHints.initializeSession(testEditor, primePump);
});
}
function tearDownTest() {
// The following call ensures that the document is reloaded
// from disk before each test
DocumentManager.closeAll();
SpecRunnerUtils.destroyMockEditor(testDoc);
testEditor = null;
testDoc = null;
}
describe("JavaScript Code Hinting Basic", function () {
beforeEach(function () {
DocumentManager.getDocumentForPath(testPath).done(function (doc) {
testDoc = doc;
});
waitsFor(function () {
return testDoc !== null;
}, "Unable to open test document", 10000);
// create Editor instance (containing a CodeMirror instance)
runs(function () {
testEditor = createMockEditor(testDoc);
JSCodeHints.initializeSession(testEditor);
});
setupTest(testPath, false);
});
afterEach(function () {
// The following call ensures that the document is reloaded
// from disk before each test
DocumentManager.closeAll();
SpecRunnerUtils.destroyMockEditor(testDoc);
testEditor = null;
testDoc = null;
tearDownTest();
});
it("should list declared variable and function names in outer scope", function () {
@@ -443,7 +468,56 @@ define(function (require, exports, module) {
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["case", "function", "var"]);
});
it("should close hints when move over '.' ", function () {
testEditor.setCursorPos({ line: 17, ch: 11 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 10 }, true);
});
it("should close hints only when move off the end of a property ", function () {
testEditor.setCursorPos({ line: 17, ch: 11 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 12 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 13 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 14 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 15 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 16 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 17 }, true);
});
it("should close hints only when move off the beginning of an identifier ", function () {
testEditor.setCursorPos({ line: 17, ch: 10 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 9 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 8 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 17, ch: 7 }, true);
});
it("should close hints only when move off the beginning of a keyword ", function () {
testEditor.setCursorPos({ line: 24, ch: 7 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresent(hintObj, ["var"]);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 24, ch: 6 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 24, ch: 5 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 24, ch: 4 }, false);
expectCloseHints(JSCodeHints.jsHintProvider, hintObj,
{ line: 24, ch: 3 }, true);
});
it("should NOT list implicit hints on left-brace", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
expectNoHints(JSCodeHints.jsHintProvider, "{");
@@ -647,6 +721,239 @@ define(function (require, exports, module) {
});
});
it("should list later defined property names", function () {
var start = { line: 17, ch: 11 };
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["foo", "propB"]);
});
});
it("should list matching property names", function () {
var start = { line: 12, ch: 10 };
testDoc.replaceRange("param", start, start);
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["paramB1", "paramB2"]);
});
});
it("should take anotation parameter type:String", function () {
var start = { line: 37, ch: 21 };
testDoc.replaceRange("var k= funD(10,11).x.", start, start);
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentOrdered(hintObj, ["charAt", "charCodeAt", "concat", "indexOf"]);
});
});
it("should take anotation parameter type:Number", function () {
var start = { line: 37, ch: 21 };
testDoc.replaceRange("var k= funD(10,11).y.", start, start);
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentOrdered(hintObj, ["toExponential", "toFixed", "toString"]);
});
});
it("should add new method on String .prototype", function () {
var start = { line: 37, ch: 0 };
var testPos = { line: 40, ch: 12 };
testDoc.replaceRange("String.prototype.times = function (count) {\n" + "\treturn count < 1 ? '' : new Array[count + 1].join(this);\n};\n\"hello\".time", start, start);
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentOrdered(hintObj, ["times", "trimLeft"]);
});
});
it("should list function defined from .prototype", function () {
var start = { line: 59, ch: 5 };
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["calc"]);
});
});
it("should list function type defined from .prototype", function () {
var start = { line: 59, ch: 10 };
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["calc(a4: number, b4: number) -> number"]);
});
});
it("should list function inhertated from super class", function () {
var start = { line: 79, ch: 11 };
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["getAmountDue", "getName", "name", "setAmountDue"]);
});
});
it("should show argument from from .prototype.Method", function () {
var start = { line: 80, ch: 0 },
testPos = { line: 80, ch: 24 };
testDoc.replaceRange("myCustomer.setAmountDue(", start);
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentOrdered(hintObj, ["setAmountDue(amountDue: ?)"]);
});
});
it("should show guessed argument type from current passing parameter", function () {
var start = { line: 80, ch: 0 },
testPos = { line: 80, ch: 24 };
testDoc.replaceRange("myCustomer.setAmountDue(10)", start);
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentOrdered(hintObj, ["setAmountDue(amountDue: number)"]);
});
});
it("should show inner function type", function () {
var testPos = { line: 96, ch: 23 };
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentOrdered(hintObj, ["innerFunc(arg: string) -> {t}"]);
});
});
it("should show type for inner function returned function", function () {
var testPos = { line: 96, ch: 33 };
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentOrdered(hintObj, ["t() -> string"]);
});
});
// parameter type anotation tests, due to another bug #3670: first argument has ?
xit("should list parameter Date,boolean type", function () {
var start = { line: 109, ch: 0 },
testPos = { line: 109, ch: 11 };
testDoc.replaceRange("funTypeAn1(", start);
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["funTypeAn1((a: bool, b: Date) -> {x, y}"]);
});
});
// parameter type anotation tests, due to another bug #3670: first argument has ?
xit("should list parameter function type and best guess for its argument/return types", function () {
var testPos = { line: 123, ch: 11 };
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["funFuncArg(f: fn() -> number) -> number"]);
});
});
// parameter type anotation tests
it("should list parameter function type and best guess for function call/return types", function () {
var testPos = { line: 139, ch: 12 };
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["funFunc2Arg(f: fn(s: string, n: number) -> string) -> string"]);
});
});
it("should list array containing functions", function () {
var testPos = { line: 142, ch: 7 };
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresent(hintObj, ["index1", "index2"]);
});
});
it("should list function reference", function () {
var start = { line: 144, ch: 0 },
testPos = { line: 144, ch: 14 };
testDoc.replaceRange("funArr.index1(", start);
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["index1() -> number"]);
});
});
it("should insert hint as [\"my-key\"] since 'my-key' is not a valid property name", function () {
var start = { line: 49, ch: 0 },
middle = { line: 49, ch: 5 },
end = { line: 49, ch: 13 };
testDoc.replaceRange("arr.m", start, start);
testEditor.setCursorPos(middle);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, "my-key");
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, end)).toEqual("arr[\"my-key\"]");
expect(testDoc.getLine(end.line).length).toEqual(13);
});
});
it("should insert hint as [\"my-key\"] make sure this works if nothing is typed after the '.'", function () {
var start = { line: 49, ch: 0 },
middle = { line: 49, ch: 4 },
end = { line: 49, ch: 13 };
testDoc.replaceRange("arr.", start, start);
testEditor.setCursorPos(middle);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, "my-key");
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, end)).toEqual("arr[\"my-key\"]");
expect(testDoc.getLine(end.line).length).toEqual(13);
});
});
it("should insert hint as '.for' since keywords can be used as property names", function () {
var start = { line: 49, ch: 0 },
middle = { line: 49, ch: 5 },
end = { line: 49, ch: 7 };
testDoc.replaceRange("arr.f", start, start);
testEditor.setCursorPos(middle);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, "for");
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, end)).toEqual("arr.for");
expect(testDoc.getLine(end.line).length).toEqual(7);
});
});
it("should jump to function", function () {
var start = { line: 43, ch: 0 };
@@ -664,8 +971,143 @@ define(function (require, exports, module) {
editorJumped({line: 3, ch: 6});
});
});
it("should jump to closure, early defined var", function () {
var start = { line: 17, ch: 9 };
testEditor.setCursorPos(start);
runs(function () {
editorJumped({line: 10, ch: 10});
});
});
// bug: the issue: timeout due to file.open command not found
xit("should jump to the definition in new module file", function () {
var start = { line: 38, ch: 21 };
testEditor.setCursorPos(start);
runs(function () {
editorJumped({line: 4, ch: 34}); //jump to another file
});
});
it("should jump to the method definition in .prototype", function () {
var start = { line: 59, ch: 8 };
testEditor.setCursorPos(start);
runs(function () {
editorJumped({line: 56, ch: 1}); //jump to prototype.calc
});
});
it("should jump to parameter passed in the method", function () {
var start = { line: 63, ch: 20 };
testEditor.setCursorPos(start);
runs(function () {
editorJumped({line: 61, ch: 27});
});
});
it("should jump to parameter passed in anonymous method", function () {
var start = { line: 83, ch: 25 };
testEditor.setCursorPos(start);
runs(function () {
editorJumped({line: 81, ch: 53});
});
});
it("should jump to inner method", function () {
var start = { line: 96, ch: 32 };
testEditor.setCursorPos(start);
runs(function () {
editorJumped({line: 94, ch: 45});
});
});
it("should not hint function, variable, or param decls", function () {
var func = { line: 7, ch: 12 },
param = { line: 7, ch: 18 },
variable = { line: 10, ch: 10 };
runs(function () {
testEditor.setCursorPos(func);
expectNoHints(JSCodeHints.jsHintProvider);
testEditor.setCursorPos(param);
expectNoHints(JSCodeHints.jsHintProvider);
testEditor.setCursorPos(variable);
expectNoHints(JSCodeHints.jsHintProvider);
});
});
});
describe("JavaScript Code Hinting in a HTML file", function () {
beforeEach(function () {
setupTest(testHtmlPath, false);
});
afterEach(function () {
tearDownTest();
});
it("basic codehints in html file", function () {
var start = { line: 30, ch: 9 },
end = { line: 30, ch: 11 };
testDoc.replaceRange("x.", start, start);
testEditor.setCursorPos(end);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentOrdered(hintObj, ["charAt", "charCodeAt", "concat", "indexOf"]);
});
});
it("function type hint in html file", function () {
var start = { line: 29, ch: 12 };
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["foo(a: number) -> string"]);
});
});
it("jump-to-def in html file", function () {
var start = { line: 29, ch: 10 };
testEditor.setCursorPos(start);
runs(function () {
editorJumped({line: 18, ch: 20});
});
});
});
describe("JavaScript Code Hinting without modules", function () {
var testPath = extensionPath + "/unittest-files/non-module-test-files/app.js";
beforeEach(function () {
setupTest(testPath, true);
});
afterEach(function () {
tearDownTest();
});
// Test reading multiple files and subdirectories
it("should handle reading all files when modules not used", function () {
var start = { line: 8, ch: 8 };
runs(function () {
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
runs(function () {
hintsPresentExact(hintObj, ["a", "b", "b1", "c", "d"]);
});
});
});
});
});
});
});