Add the JS code hinter as a default extension.

This commit is contained in:
Ian Wehrman committed 2013-02-14 15:59:12 -08:00
1 parent 89f70f3e3b
commit 786cd23bce
12 files changed
+7024

No files matched your search

@@ -0,0 +1,294 @@
/*
* Copyright (c) 2012 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define */
define(function (require, exports, module) {
"use strict";
var MODE_NAME = "javascript",
SCOPE_MSG_TYPE = "outerScope",
SINGLE_QUOTE = "\'",
DOUBLE_QUOTE = "\"";
function makeToken(value, positions) {
if (positions === undefined) {
positions = [];
}
return {
value: value,
positions: positions
};
}
/**
* Is the string key perhaps a valid JavaScript identifier?
*/
function maybeIdentifier(key) {
return (/[0-9a-z_.\$]/i).test(key) ||
(key.indexOf("\"") === 0) || (key.indexOf("\'") === 0);
}
/**
* Is the token's class hintable?
*/
function hintable(token) {
switch (token.className) {
case "comment":
case "number":
case "regexp":
return false;
default:
return true;
}
}
/**
* Divide a path into directory and filename parts
*/
function splitPath(path) {
var index = path.lastIndexOf("/"),
dir = path.substring(0, index),
file = path.substring(index, path.length);
return {dir: dir, file: file };
}
/*
* Get a JS-hints-specific event name
*/
function eventName(name) {
var EVENT_TAG = "brackets-js-hints";
return name + "." + EVENT_TAG;
}
/*
* Annotate list of identifiers with their scope level
*/
function annotateWithScope(identifiers, scope) {
return identifiers.map(function (t) {
var level = scope.contains(t.value);
if (level >= 0) {
t.level = level;
} else {
t.level = -1;
}
return t;
});
}
/*
* Annotate a list of properties with their association level
*/
function annotateWithAssociation(properties, association) {
return properties.map(function (t) {
if (association[t.value] > 0) {
t.level = 0;
}
return t;
});
}
/*
* Annotate a list of tokens as being global variables
*/
function annotateGlobals(globals) {
return globals.map(function (t) {
t.global = true;
return t;
});
}
/*
* Annotate a list of tokens as literals of a particular kind;
* if string literals, annotate with an appropriate delimiter.
*/
function annotateLiterals(literals, kind) {
return literals.map(function (t) {
t.literal = true;
t.kind = kind;
if (/[\\\\]*[^\\]"/.test(t.value)) {
t.delimeter = SINGLE_QUOTE;
} else {
t.delimeter = DOUBLE_QUOTE;
}
return t;
});
}
/*
* Annotate a list of tokens as keywords
*/
function annotateKeywords(keywords) {
return keywords.map(function (t) {
t.keyword = true;
return t;
});
}
/*
* Annotate a list of tokens as keywords
*/
function annotateWithPath(tokens, dir, file) {
var path = dir + file;
return tokens.map(function (t) {
t.path = path;
return t;
});
}
var KEYWORD_NAMES = [
"break", "case", "catch", "continue", "debugger", "default", "delete",
"do", "else", "finally", "for", "function", "if", "in", "instanceof",
"new", "return", "switch", "this", "throw", "try", "typeof", "var",
"void", "while", "with"
],
KEYWORD_TOKENS = KEYWORD_NAMES.map(function (t) { return makeToken(t, []); }),
KEYWORDS = annotateKeywords(KEYWORD_TOKENS);
var LITERAL_NAMES = [
"true", "false", "null", "undefined"
],
LITERAL_TOKENS = LITERAL_NAMES.map(function (t) { return makeToken(t, []); }),
LITERALS = annotateLiterals(LITERAL_TOKENS);
var JSL_GLOBALS = [
"clearInterval", "clearTimeout", "document", "event", "frames",
"history", "Image", "location", "name", "navigator", "Option",
"parent", "screen", "setInterval", "setTimeout", "window",
"XMLHttpRequest", "alert", "confirm", "console", "Debug", "opera",
"prompt", "WSH", "Buffer", "exports", "global", "module", "process",
"querystring", "require", "__filename", "__dirname", "defineClass",
"deserialize", "gc", "help", "load", "loadClass", "print", "quit",
"readFile", "readUrl", "runCommand", "seal", "serialize", "spawn",
"sync", "toint32", "version", "ActiveXObject", "CScript", "Enumerator",
"System", "VBArray", "WScript"
].reduce(function (prev, curr) {
prev[curr] = makeToken(curr);
return prev;
}, {});
var JSL_GLOBALS_BROWSER = [
JSL_GLOBALS.clearInterval,
JSL_GLOBALS.clearTimeout,
JSL_GLOBALS.document,
JSL_GLOBALS.event,
JSL_GLOBALS.frames,
JSL_GLOBALS.history,
JSL_GLOBALS.Image,
JSL_GLOBALS.location,
JSL_GLOBALS.name,
JSL_GLOBALS.navigator,
JSL_GLOBALS.Option,
JSL_GLOBALS.parent,
JSL_GLOBALS.screen,
JSL_GLOBALS.setInterval,
JSL_GLOBALS.setTimeout,
JSL_GLOBALS.window,
JSL_GLOBALS.XMLHttpRequest
],
JSL_GLOBALS_DEVEL = [
JSL_GLOBALS.alert,
JSL_GLOBALS.confirm,
JSL_GLOBALS.console,
JSL_GLOBALS.Debug,
JSL_GLOBALS.opera,
JSL_GLOBALS.prompt,
JSL_GLOBALS.WSH
],
JSL_GLOBALS_NODE = [
JSL_GLOBALS.Buffer,
JSL_GLOBALS.clearInterval,
JSL_GLOBALS.clearTimeout,
JSL_GLOBALS.console,
JSL_GLOBALS.exports,
JSL_GLOBALS.global,
JSL_GLOBALS.module,
JSL_GLOBALS.process,
JSL_GLOBALS.querystring,
JSL_GLOBALS.require,
JSL_GLOBALS.setInterval,
JSL_GLOBALS.setTimeout,
JSL_GLOBALS.__filename,
JSL_GLOBALS.__dirname
],
JSL_GLOBALS_RHINO = [
JSL_GLOBALS.defineClass,
JSL_GLOBALS.deserialize,
JSL_GLOBALS.gc,
JSL_GLOBALS.help,
JSL_GLOBALS.load,
JSL_GLOBALS.loadClass,
JSL_GLOBALS.print,
JSL_GLOBALS.quit,
JSL_GLOBALS.readFile,
JSL_GLOBALS.readUrl,
JSL_GLOBALS.runCommand,
JSL_GLOBALS.seal,
JSL_GLOBALS.serialize,
JSL_GLOBALS.spawn,
JSL_GLOBALS.sync,
JSL_GLOBALS.toint32,
JSL_GLOBALS.version
],
JSL_GLOBALS_WINDOWS = [
JSL_GLOBALS.ActiveXObject,
JSL_GLOBALS.CScript,
JSL_GLOBALS.Debug,
JSL_GLOBALS.Enumerator,
JSL_GLOBALS.System,
JSL_GLOBALS.VBArray,
JSL_GLOBALS.WScript,
JSL_GLOBALS.WSH
];
var JSL_GLOBAL_DEFS = {
browser : JSL_GLOBALS_BROWSER,
devel : JSL_GLOBALS_DEVEL,
node : JSL_GLOBALS_NODE,
rhino : JSL_GLOBALS_RHINO,
windows : JSL_GLOBALS_WINDOWS
};
exports.makeToken = makeToken;
exports.hintable = hintable;
exports.maybeIdentifier = maybeIdentifier;
exports.splitPath = splitPath;
exports.eventName = eventName;
exports.annotateWithPath = annotateWithPath;
exports.annotateLiterals = annotateLiterals;
exports.annotateGlobals = annotateGlobals;
exports.annotateWithScope = annotateWithScope;
exports.annotateWithAssociation = annotateWithAssociation;
exports.JSL_GLOBAL_DEFS = JSL_GLOBAL_DEFS;
exports.KEYWORDS = KEYWORDS;
exports.LITERALS = LITERALS;
exports.MODE_NAME = MODE_NAME;
exports.SCOPE_MSG_TYPE = SCOPE_MSG_TYPE;
exports.SINGLE_QUOTE = SINGLE_QUOTE;
exports.DOUBLE_QUOTE = DOUBLE_QUOTE;
});
@@ -0,0 +1,632 @@
/*
* Copyright (c) 2012 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define(function (require, exports, module) {
"use strict";
function Scope(tree, parent) {
/*
* Given a member expression, try to add a target-property association
* to the given scope.
*/
function _buildAssociations(object, property, parent) {
if (property.type === "Identifier") {
if (object.type === "Identifier") {
parent.addAssociation(object, property);
} else if (object.type === "MemberExpression") {
if (object.computed === false) {
_buildAssociations(object.property, property, parent);
}
} else if (object.type === "CallExpression") {
_buildAssociations(object.callee, property, parent);
} else if (object.type === "ThisExpression") {
object.name = "this";
parent.addAssociation(object, property);
} else {
// most likely a call expression or a literal
return;
}
} else {
// Because we restrict to non-computed property lookups, this
// should be unreachable
throw "Expected identifier but found " + property.type;
}
}
/*
* Build scope information for an AST as a child scope of parent.
*/
function _buildScope(tree, parent) {
var child;
if (tree === undefined || tree === null) {
return;
}
switch (tree.type) {
case "Program":
case "BlockStatement":
tree.body.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "FunctionDeclaration":
parent.addDeclaration(tree.id);
_buildScope(tree.id, parent);
child = new Scope(tree, parent);
child.addAllDeclarations(tree.params);
tree.params.forEach(function (t) {
_buildScope(t, child);
});
parent.addChildScope(child);
_buildScope(tree.body, child);
break;
case "VariableDeclaration":
// FIXME handle let scoping
tree.declarations.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "VariableDeclarator":
parent.addDeclaration(tree.id);
_buildScope(tree.id, parent);
if (tree.init !== null) {
_buildScope(tree.init, parent);
}
break;
case "ExpressionStatement":
_buildScope(tree.expression, parent);
break;
case "SwitchStatement":
_buildScope(tree.discriminant, parent);
if (tree.cases) {
tree.cases.forEach(function (t) {
_buildScope(t, parent);
});
}
break;
case "SwitchCase":
tree.consequent.forEach(function (t) {
_buildScope(t, parent);
});
if (tree.test) {
_buildScope(tree.test, parent);
}
break;
case "TryStatement":
tree.handlers.forEach(function (t) {
_buildScope(t, parent);
});
_buildScope(tree.block, parent);
if (tree.finalizer) {
_buildScope(tree.finalizer, parent);
}
break;
case "ThrowStatement":
_buildScope(tree.argument, parent);
break;
case "WithStatement":
_buildScope(tree.object, parent);
_buildScope(tree.body, parent);
break;
case "CatchClause":
if (tree.guard) {
_buildScope(tree.guard, parent);
}
// FIXME: Is this the correct way to handle catch?
child = new Scope(tree, parent);
child.addDeclaration(tree.param);
_buildScope(tree.param, child);
parent.addChildScope(child);
_buildScope(tree.body, child);
break;
case "ReturnStatement":
if (tree.argument) {
_buildScope(tree.argument, parent);
}
break;
case "ForStatement":
_buildScope(tree.body, parent);
if (tree.init) {
_buildScope(tree.init, parent);
}
if (tree.test) {
_buildScope(tree.test, parent);
}
if (tree.update) {
_buildScope(tree.update, parent);
}
break;
case "ForInStatement":
_buildScope(tree.left, parent);
_buildScope(tree.right, parent);
_buildScope(tree.body, parent);
break;
case "LabeledStatement":
_buildScope(tree.body, parent);
break;
case "BreakStatement":
case "ContinueStatement":
if (tree.label) {
_buildScope(tree.label, parent);
}
break;
case "UpdateExpression":
case "UnaryExpression":
_buildScope(tree.argument, parent);
break;
case "IfStatement":
case "ConditionalExpression":
_buildScope(tree.test, parent);
_buildScope(tree.consequent, parent);
if (tree.alternate) {
_buildScope(tree.alternate, parent);
}
break;
case "WhileStatement":
case "DoWhileStatement":
_buildScope(tree.test, parent);
_buildScope(tree.body, parent);
break;
case "SequenceExpression":
tree.expressions.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "ObjectExpression":
tree.properties.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "ArrayExpression":
tree.elements.forEach(function (t) {
_buildScope(t, parent);
});
break;
case "NewExpression":
if (tree['arguments']) { // pacifies JSLint
tree['arguments'].forEach(function (t) {
_buildScope(t, parent);
});
}
_buildScope(tree.callee, parent);
break;
case "BinaryExpression":
case "AssignmentExpression":
case "LogicalExpression":
_buildScope(tree.left, parent);
_buildScope(tree.right, parent);
break;
case "MemberExpression":
_buildScope(tree.object, parent);
_buildScope(tree.property, parent);
if (tree.property && tree.property.type === "Identifier") {
parent.addProperty(tree.property);
}
if (tree.computed === false) {
_buildAssociations(tree.object, tree.property, parent);
}
break;
case "CallExpression":
tree['arguments'].forEach(function (t) {
_buildScope(t, parent);
});
_buildScope(tree.callee, parent);
break;
case "FunctionExpression":
if (tree.id) {
parent.addDeclaration(tree.id);
_buildScope(tree.id, parent);
}
child = new Scope(tree, parent);
parent.addChildScope(child);
child.addAllDeclarations(tree.params);
tree.params.forEach(function (t) {
_buildScope(t, child);
});
_buildScope(tree.body, child);
break;
case "Property":
// Undocumented or Esprima-specific?
parent.addProperty(tree.key);
_buildScope(tree.value, parent);
break;
case "Identifier":
parent.addIdOccurrence(tree);
break;
case "Literal":
if (tree.value && typeof tree.value === "string") {
parent.addLiteralOccurrence(tree);
}
break;
case "DebuggerStatement":
case "EmptyStatement":
case "ThisExpression":
break;
default:
throw "Unknown node type: " + tree.type;
}
}
if (parent === undefined) {
this.parent = null;
} else {
this.parent = parent;
}
this.idDeclarations = [];
this.idOccurrences = [];
this.propOccurrences = [];
this.associations = [];
this.literals = [];
this.children = []; // disjoint ranges, ordered by range start
this.range = {
start: tree.range[0],
end: tree.range[1]
};
// if parent is null, walk the AST
if (!this.parent) {
_buildScope(tree, this);
}
}
/*
* Rebuild a Scope object from an object that has all the necessary data
* but the wrong prototype. Such objects may be created as a result of
* e.g., JSON-marshalling and unmarshalling a scope.
*/
Scope.rebuild = function (data) {
var memberName,
member;
for (memberName in Scope.prototype) {
if (Scope.prototype.hasOwnProperty(memberName)) {
member = Scope.prototype[memberName];
if (typeof member === "function") {
data[memberName] = member;
}
}
}
data.children.forEach(function (child) {
Scope.rebuild(child);
});
return data;
};
/*
* Add an identifier occurrence.
*/
Scope.prototype.addIdOccurrence = function (id) {
this.idOccurrences.push(id);
};
/*
* Add an identifier declaration
*/
Scope.prototype.addDeclaration = function (id) {
this.idDeclarations.push(id);
this.addIdOccurrence(id);
};
/*
* Add a list of identifier declarations
*/
Scope.prototype.addAllDeclarations = function (ids) {
var that = this;
ids.forEach(function (i) {
that.idDeclarations.push(i);
});
};
/*
* Add a property occurrence
*/
Scope.prototype.addProperty = function (prop) {
this.propOccurrences.push(prop);
};
/*
* Add an association object
*/
Scope.prototype.addAssociation = function (obj, prop) {
this.associations.push({object: obj, property: prop});
};
/*
* Add a literal occurrence
*/
Scope.prototype.addLiteralOccurrence = function (lit) {
this.literals.push(lit);
};
/*
* Attach a new child scope to the current scope
*/
Scope.prototype.addChildScope = function (child) {
var i = 0;
while (i < this.children.length &&
child.range.start > this.children[i].range.end) {
i++;
}
this.children.splice(i, 0, child);
};
/*
* Find the child scope of the current scope for a given position
*/
Scope.prototype.findChild = function (pos) {
var i;
if (this.range.start <= pos && pos <= this.range.end) {
for (i = 0; i < this.children.length; i++) {
if (this.children[i].range.start <= pos &&
pos <= this.children[i].range.end) {
return this.children[i].findChild(pos);
}
}
// if no child has a matching range, this is the most precise scope
return this;
} else {
return null;
}
};
/*
* Is the symbol declared in this scope?
*/
Scope.prototype.member = function (sym) {
var i;
for (i = 0; i < this.idDeclarations.length; i++) {
if (this.idDeclarations[i].name === sym) {
return true;
}
}
return false;
};
/*
* Is the symbol declared in this scope or a parent scope?
*/
Scope.prototype.contains = function (sym) {
var depth = 0,
child = this;
do {
if (child.member(sym)) {
return depth;
} else {
child = child.parent;
depth++;
}
} while (child !== null);
return undefined;
};
/*
* Does this scope, or its children, contain the given position?
*/
Scope.prototype.containsPosition = function (pos) {
return this.range.start <= pos && pos <= this.range.end;
};
/*
* Does this scope, but not its children, contain the given position?
*/
Scope.prototype.containsPositionImmediate = function (pos) {
var children = this.children,
i;
// is in the scope's range...
if (this.containsPosition(pos)) {
for (i = 0; i < children.length; i++) {
// but not in a child's scope
if (children[i].containsPosition(pos)) {
return false;
}
}
return true;
} else {
return false;
}
};
/**
* Traverse the scope down via children
*/
Scope.prototype.walkDown = function (add, init) {
var result = add(this, init);
this.children.forEach(function (child) {
result = child.walkDown(add, result);
});
return result;
};
/*
* Traverse a particular list in the scope down via children
*/
Scope.prototype.walkDownList = function (addItem, init, listName) {
function addList(scope, init) {
var list = scope[listName];
return list.reduce(function (prev, curr) {
return addItem(prev, curr);
}, init);
}
return this.walkDown(addList, init);
};
/*
* Traverse identifier declarations in the scope down via children
*/
Scope.prototype.walkDownDeclarations = function (add, init) {
return this.walkDownList(add, init, 'idDeclarations');
};
/*
* Traverse identifier occurrences in the scope down via children
*/
Scope.prototype.walkDownIdentifiers = function (add, init) {
return this.walkDownList(add, init, 'idOccurrences');
};
/*
* Traverse property occurrences in the scope down via children
*/
Scope.prototype.walkDownProperties = function (add, init) {
return this.walkDownList(add, init, 'propOccurrences');
};
/*
* Traverse associations in the scope down via children
*/
Scope.prototype.walkDownAssociations = function (add, init) {
return this.walkDownList(add, init, 'associations');
};
/*
* Traverse literals in the scope down via children
*/
Scope.prototype.walkDownLiterals = function (add, init) {
return this.walkDownList(add, init, 'literals');
};
/**
* Traverse the scope up via the parent
*/
Scope.prototype.walkUp = function (add, init, prop) {
var scope = this,
result = init,
i;
while (scope !== null) {
for (i = 0; i < this[prop].length; i++) {
result = add(result, this[prop][i]);
}
scope = scope.parent;
}
return result;
};
/**
* Traverse identifier declarations in the scope up via the parent
*/
Scope.prototype.walkUpDeclarations = function (add, init) {
return this.walkUp(add, init, 'idDeclarations');
};
/**
* Traverse identifier occurrences in the scope up via the parent
*/
Scope.prototype.walkUpIdentifiers = function (add, init) {
return this.walkUp(add, init, 'idOccurrences');
};
/**
* Traverse property occurrences in the scope up via the parent
*/
Scope.prototype.walkUpProperties = function (add, init) {
return this.walkUp(add, init, 'propOccurrences');
};
/**
* Traverse associations in the scope up via the parent
*/
Scope.prototype.walkUpAssociations = function (add, init) {
return this.walkUp(add, init, 'associations');
};
/**
* Traverse literal occurrences in the scope up via the parent
*/
Scope.prototype.walkUpLiterals = function (add, init) {
return this.walkUp(add, init, 'literals');
};
/**
* Return a string representations of declarations below this scope
*/
Scope.prototype.toStringBelow = function () {
return "[" + this.range.start + " " + this.idDeclarations.map(function (i) {
return i.name;
}).join(", ") +
" : " + (this.children.map(function (c) {
return c.toString();
}).join("; ")) + this.range.end + "]";
};
/**
* Return a string representations of declarations in this scope
*/
Scope.prototype.toString = function () {
return "[" + this.range.start + " " + this.idDeclarations.map(function (i) {
return i.name;
}).join(", ") + this.range.end + "]";
};
module.exports = Scope;
});
@@ -0,0 +1,488 @@
/*
* Copyright (c) 2012 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.
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, Worker */
define(function (require, exports, module) {
"use strict";
var DocumentManager = brackets.getModule("document/DocumentManager"),
EditorUtils = brackets.getModule("editor/EditorUtils"),
FileUtils = brackets.getModule("file/FileUtils"),
NativeFileSystem = brackets.getModule("file/NativeFileSystem").NativeFileSystem,
ProjectManager = brackets.getModule("project/ProjectManager"),
HintUtils = require("HintUtils"),
Scope = require("Scope");
var pendingRequest = null, // information about a deferred scope request
fileState = {}, // directory -> file -> state
outerScopeWorker = (function () {
var path = module.uri.substring(0, module.uri.lastIndexOf("/") + 1);
return new Worker(path + "parser-worker.js");
}());
/*
* Initialize state for a given directory and file name
*/
function initFileState(dir, file) {
// initialize outerScope, etc. at dir
if (!fileState.hasOwnProperty(dir)) {
fileState[dir] = {};
}
if (file !== undefined) {
if (!fileState[dir].hasOwnProperty(file)) {
fileState[dir][file] = {
// global scope object for this file
scope : null,
// has the file changed since the scope was updated?
dirtyFile : true,
// has the scope changed since the last inner scope request?
dirtyScope : true,
// is the parser worker active for this file?
active : false,
// all variable and parameter names defined in this file
identifiers : null,
// all property names found in this file
properties : null,
// all globals defined in this file
globals : null,
// all string literals found in this file
literals : null,
// all context-property associations found in this file
associations : null
};
}
}
}
function getFileState(dir, file) {
initFileState(dir, file);
if (file === undefined) {
return fileState[dir];
} else {
return fileState[dir][file];
}
}
/**
* Request a new outer scope object from the parser worker, if necessary
*/
function refreshOuterScope(dir, file, text) {
var state = getFileState(dir, file);
// if there is not yet an outer scope or if the file has changed then
// we might need to update the outer scope
if (state.scope === null || state.dirtyFile) {
if (!state.active) {
var path = dir + file,
entry = new NativeFileSystem.FileEntry(path);
// the outer scope worker is about to be active
state.active = true;
// 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
});
}
}
}
/**
* Recompute the inner scope for a given cursor position, if necessary
*/
function refreshInnerScope(dir, file, offset) {
/*
* Filter a list of tokens using a given scope object
*/
function filterByScope(tokens, scope) {
return tokens.filter(function (id) {
var level = scope.contains(id.value);
return (level >= 0);
});
}
/*
* Combine a set of sets using the add operation
*/
function merge(sets, property, add) {
var combinedSet = {},
nextSet,
file;
for (file in sets) {
if (sets.hasOwnProperty(file)) {
nextSet = sets[file][property];
if (nextSet) {
add(combinedSet, nextSet);
}
}
}
return combinedSet;
}
/*
* Combine properties from files in the current file's directory into
* one sorted list.
*/
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 objects from multiple files
*/
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.
if (!state.scope) {
if (pendingRequest && pendingRequest.deferred.state() === "pending") {
pendingRequest.deferred.reject();
}
pendingRequest = {
dir : dir,
file : file,
offset : offset,
deferred : $.Deferred()
};
// Request the outer scope from the parser worker.
DocumentManager.getDocumentForPath(dir + file).done(function (document) {
refreshOuterScope(dir, file, document.getText());
});
return { promise: pendingRequest.deferred.promise() };
} else {
// The inner scope will be clean after this
state.dirtyScope = false;
// Try to find an inner scope from the current outer scope
var innerScope = state.scope.findChild(offset);
if (!innerScope) {
// we may have failed to find a child scope because a
// character was added to the end of the file, outside of
// the (now out-of-date and currently-being-updated)
// outer scope. Hence, if offset is greater than the range
// of the outerScope, we manually set innerScope to the
// outerScope
innerScope = state.scope;
}
// FIXME: This could be more efficient if instead of filtering
// the entire list of identifiers we just used the identifiers
// in the scope of innerScope, but that list doesn't have the
// accumulated position information.
var identifiersForScope = filterByScope(state.identifiers, innerScope),
propertiesForFile = mergeProperties(dir),
associationsForFile = mergeAssociations(dir);
return {
scope: innerScope,
identifiers: identifiersForScope,
globals: state.globals,
literals: state.literals,
properties: propertiesForFile,
associations: associationsForFile
};
}
}
/**
* Get a new inner scope and related info, if possible. If there is no
* outer scope for the given file, a deferred object will be returned
* instead.
*
* Note that successive calls to getScope may return the same objects, so
* clients that wish to modify those objects (e.g., by annotating them based
* on some temporary context) should copy them first. See, e.g.,
* Session.getHints().
*/
function getScopeInfo(document, offset) {
var path = document.file.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
file = split.file;
return refreshInnerScope(dir, file, offset);
}
/**
* Is the inner scope dirty? (It is if the outer scope has changed since
* the last inner scope request)
*/
function isScopeDirty(document) {
var path = document.file.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
file = split.file,
state = getFileState(dir, file);
return state.dirtyScope;
}
/**
* Mark a file as dirty, which causes an outer scope request to trigger
* a reparse request.
*/
function markFileDirty(dir, file) {
var state = getFileState(dir, file);
state.dirtyFile = true;
}
/**
* Refresh the outer scopes of the given file as well as of the other files
* in the given directory.
*/
function handleEditorChange(document) {
var path = document.file.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
file = split.file,
dirEntry = new NativeFileSystem.DirectoryEntry(dir),
reader = dirEntry.createReader();
markFileDirty(dir, file);
reader.readEntries(function (entries) {
entries.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 mode = EditorUtils.getModeFromFileExtension(entry.fullPath);
if (mode === HintUtils.MODE_NAME) {
DocumentManager.getDocumentForPath(path).done(function (document) {
refreshOuterScope(dir, file, document.getText());
});
}
}
}
});
}, function (err) {
console.log("Unable to refresh directory: " + err);
refreshOuterScope(dir, file, document.getText());
});
}
/*
* When a file changes, mark it as being dirty and refresh its outer scope.
*/
function handleFileChange(document) {
var path = document.file.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
file = split.file;
markFileDirty(dir, file);
refreshOuterScope(dir, file, document.getText());
}
/*
* Receive an outer scope object from the parser worker
*/
function handleOuterScope(response) {
var dir = response.dir,
file = response.file,
path = dir + file,
state = getFileState(dir, file),
scopeInfo;
if (state.active) {
state.active = false;
if (response.success) {
state.scope = Scope.rebuild(response.scope);
// The outer scope should cover the entire file
state.scope.range.start = 0;
state.scope.range.end = response.length;
state.globals = response.globals;
state.identifiers = response.identifiers;
state.properties = response.properties;
state.literals = response.literals;
state.associations = response.associations;
state.dirtyScope = true;
if (state.dirtyFile) {
DocumentManager.getDocumentForPath(path).done(function (document) {
refreshOuterScope(dir, file, document.getText());
});
}
if (pendingRequest !== null && pendingRequest.dir === dir &&
pendingRequest.file === file) {
if (pendingRequest.deferred.state() === "pending") {
scopeInfo = refreshInnerScope(dir, file, pendingRequest.offset);
if (scopeInfo && !scopeInfo.deferred) {
pendingRequest.deferred.resolveWith(null, [scopeInfo]);
pendingRequest = null;
}
}
}
}
} else {
console.log("Expired scope request: " + path);
}
}
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));
}
});
// reset state on project change
$(ProjectManager)
.on(HintUtils.eventName("beforeProjectClose"),
function (event, projectRoot) {
fileState = {};
});
// relocate scope information on file rename
$(DocumentManager)
.on(HintUtils.eventName("fileNameChange"),
function (event, oldname, newname) {
var oldsplit = HintUtils.splitPath(oldname),
olddir = oldsplit.dir,
oldfile = oldsplit.file,
newsplit = HintUtils.splitPath(newname),
newdir = newsplit.dir,
newfile = newsplit.file;
/*
* Move property obj[olddir][oldfile] to obj[newdir][newfile]
*/
function moveProp(obj) {
if (obj.hasOwnProperty(olddir) && obj[olddir].hasOwnProperty(oldfile)) {
if (!obj.hasOwnProperty(newdir)) {
obj[newdir] = {};
}
obj[newdir][newfile] = obj[olddir][oldfile];
delete obj[olddir][oldfile];
}
}
moveProp(fileState);
});
exports.handleEditorChange = handleEditorChange;
exports.handleFileChange = handleFileChange;
exports.getScopeInfo = getScopeInfo;
exports.isScopeDirty = isScopeDirty;
});
@@ -0,0 +1,463 @@
/*
* Copyright (c) 2012 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets, $ */
define(function (require, exports, module) {
"use strict";
var HintUtils = require("HintUtils"),
ScopeManager = require("ScopeManager");
/**
* Session objects encapsulate state associated with a hinting session
* and provide methods for updating and querying the session.
*/
function Session(editor) {
this.editor = editor;
this.path = editor.document.file.fullPath;
}
/**
* Update the scope information assocated with the current session
*/
Session.prototype.setScopeInfo = function (scopeInfo) {
this.scope = scopeInfo.scope;
this.identifiers = scopeInfo.identifiers;
this.globals = scopeInfo.globals;
this.literals = scopeInfo.literals;
this.properties = scopeInfo.properties;
this.associations = scopeInfo.associations;
};
/**
* Get the name of the file associated with the current session
*/
Session.prototype.getPath = function () {
return this.path;
};
/**
* Get the current cursor position.
*
* @return Object<line: number, ch, number>
*/
Session.prototype.getCursor = function () {
return this.editor.getCursorPos();
};
/**
* Get the offset of the current cursor position
*/
Session.prototype.getOffset = function () {
var cursor = this.getCursor();
return this.editor.indexFromPos(cursor);
};
/**
* Get the token at the given cursor position, or at the current cursor
* if none is given.
*/
Session.prototype.getToken = function (cursor) {
var cm = this.editor._codeMirror;
if (cursor) {
return cm.getTokenAt(cursor);
} else {
return cm.getTokenAt(this.getCursor());
}
};
/**
* Get the next cursor position on the line, or null if there isn't one.
*/
Session.prototype.getNextCursorOnLine = function () {
var cursor = this.getCursor(),
doc = this.editor.document,
line = doc.getLine(cursor.line);
if (cursor.ch < line.length) {
return {
ch : cursor.ch + 1,
line: cursor.line
};
} else {
return null;
}
};
/**
* Get the token before the one at the given cursor
*/
Session.prototype._getPreviousToken = function (cursor) {
var token = this.getToken(cursor),
prev = token,
doc;
do {
if (prev.start < cursor.ch) {
cursor.ch = prev.start;
} else if (prev.start > 0) {
cursor.ch = prev.start - 1;
} else if (cursor.line > 0) {
doc = this.editor.document;
cursor.ch = doc.getLine(cursor.line - 1).length;
cursor.line--;
} else {
break;
}
prev = this.getToken(cursor);
} while (prev.string.trim() === "");
return prev;
};
/**
* Calculate a query string relative to the current cursor position
* and token.
*/
Session.prototype.getQuery = function () {
var cursor = this.getCursor(),
token = this.getToken(cursor),
query = "";
if (token) {
if (token.string !== ".") {
query = token.string.substring(0, token.string.length - (token.end - cursor.ch));
query = query.trim();
}
}
return query;
};
/**
* Find the context of a property lookup. For example, for a lookup
* foo(bar, baz(quux)).prop, foo is the context.
*/
Session.prototype.getContext = function (cursor, depth) {
var token = this.getToken(cursor);
if (depth === undefined) {
depth = 0;
}
if (token.string === ")") {
this._getPreviousToken(cursor);
return this.getContext(cursor, ++depth);
} else if (token.string === "(") {
this._getPreviousToken(cursor);
return this.getContext(cursor, --depth);
} else {
if (depth > 0 || token.string === ".") {
this._getPreviousToken(cursor);
return this.getContext(cursor, depth);
} else {
return token.string;
}
}
};
/**
* Get the type of the type of the current session, i.e., whether it is a
* property lookup and, if so, what the context of the lookup is.
*/
Session.prototype.getType = function () {
var propertyLookup = false,
context = null,
cursor = this.getCursor(),
token = this.getToken(cursor);
if (token) {
if (token.string === ".") {
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);
}
}
}
return {
property: propertyLookup,
context: context
};
};
/**
* Get a list of hints for the current session using the current scope information.
*/
Session.prototype.getHints = function () {
/*
* Comparator for sorting tokens according to minimum distance from
* a given position
*/
function compareByPosition(pos) {
/*
* Compute the minimum distance between a token, with which is
* associated a sorted list of positions, and a given offset.
*/
function mindist(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) {
/*
* Lookup the cached minimum distance from an occurrence of the
* token to the given position, calculating and storing it if
* needed.
*/
function getDistToPos(token) {
var dist;
if (token.distToPos >= 0) {
dist = token.distToPos;
} else {
dist = mindist(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.
*/
function compareByScope(a, b) {
var adepth = a.level;
var bdepth = b.level;
if (adepth >= 0) {
if (bdepth >= 0) {
return adepth - bdepth;
} else {
return -1;
}
} else {
if (bdepth >= 0) {
return 1;
} else {
return 0;
}
}
}
/*
* Comparator for sorting tokens by name
*/
function compareByName(a, b) {
if (a.value === b.value) {
return 0;
} else if (a.value < b.value) {
return -1;
} else {
return 1;
}
}
/*
* Comparator for sorting tokens by path, such that
* a <= b if a.path === path
*/
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.
*/
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
*/
function lexicographic(compare1, compare2) {
return function (a, b) {
var result = compare1(a, b);
if (result === 0) {
return compare2(a, b);
} else {
return result;
}
};
}
/*
* A comparator for identifiers
*/
function compareIdentifiers(pos) {
return lexicographic(compareByScope,
lexicographic(compareByPosition(pos),
compareByName));
}
/*
* A comparator for properties
*/
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.)
*/
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);
}
var cursor = this.editor.getCursorPos(),
offset = this.editor.indexFromPos(cursor),
type = this.getType(),
association,
hints;
if (type.property) {
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 = hints.concat(HintUtils.LITERALS);
hints = hints.concat(HintUtils.KEYWORDS);
}
return hints;
};
module.exports = Session;
});
@@ -0,0 +1,414 @@
/*
* Copyright (c) 2012 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets, $ */
define(function (require, exports, module) {
"use strict";
var CodeHintManager = brackets.getModule("editor/CodeHintManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
AppInit = brackets.getModule("utils/AppInit"),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
StringUtils = brackets.getModule("utils/StringUtils"),
HintUtils = require("HintUtils"),
ScopeManager = require("ScopeManager"),
Session = require("Session");
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;
/**
* Creates a hint response object. Filters the hint list using the query
* string, formats the hints for display, and returns a hint response
* object according to the CodeHintManager's API for code hint providers.
*/
function getHintResponse(hints, query) {
var trimmedQuery,
filteredHints,
formattedHints;
/*
* Filter a list of tokens using a given query string
*/
function filterWithQuery(tokens, limit) {
/*
* Filter arr using test, returning at most limit results from the
* front of the array.
*/
function filterArrayPrefix(arr, test, limit) {
var i = 0,
results = [],
elem;
for (i; i < arr.length && results.length <= limit; i++) {
elem = arr[i];
if (test(elem)) {
results.push(elem);
}
}
return results;
}
// If the query is a string literal (i.e., if it starts with a
// string literal delimiter, and hence if trimmedQuery !== query)
// then only string literal hints should be returned, and matching
// should be performed w.r.t. trimmedQuery. If the query is
// otherwise non-empty, no string literals should match. If the
// query is empty then no hints are filtered.
if (trimmedQuery !== query) {
return filterArrayPrefix(tokens, function (token) {
if (token.literal && token.kind === "string") {
return (token.value.indexOf(trimmedQuery) === 0);
} else {
return false;
}
}, limit);
} else if (query.length > 0) {
return filterArrayPrefix(tokens, function (token) {
if (token.literal && token.kind === "string") {
return false;
} else {
return (token.value.indexOf(query) === 0);
}
}, limit);
} else {
return tokens.slice(0, limit);
}
}
/*
* Returns a formatted list of hints with the query substring highlighted
*/
function formatHints(hints, query) {
return hints.map(function (token) {
var hint = token.value,
index = hint.indexOf(query),
$hintObj = $("<span>").addClass("brackets-js-hints"),
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;
}
// is the token a global variable?
if (token.global) {
$hintObj.addClass("global-hint");
}
// is the token a literal?
if (token.literal) {
$hintObj.addClass("literal-hint");
if (token.kind === "string") {
delimiter = HintUtils.DOUBLE_QUOTE;
}
}
// is the token a keyword?
if (token.keyword) {
$hintObj.addClass("keyword-hint");
}
// higlight the matched portion of each hint
if (index >= 0) {
var prefix = StringUtils.htmlEscape(hint.slice(0, index)),
match = StringUtils.htmlEscape(hint.slice(index, index + query.length)),
suffix = StringUtils.htmlEscape(hint.slice(index + query.length));
$hintObj.append(delimiter + prefix)
.append($("<span>")
.append(match)
.addClass("matched-hint"))
.append(suffix + delimiter);
} else {
$hintObj.text(delimiter + hint + delimiter);
}
$hintObj.data("token", token);
return $hintObj;
});
}
// trim leading and trailing string literal delimiters from the query
if (query.indexOf(HintUtils.SINGLE_QUOTE) === 0 ||
query.indexOf(HintUtils.DOUBLE_QUOTE) === 0) {
trimmedQuery = query.substring(1);
if (trimmedQuery.lastIndexOf(HintUtils.DOUBLE_QUOTE) === trimmedQuery.length - 1 ||
trimmedQuery.lastIndexOf(HintUtils.SINGLE_QUOTE) === trimmedQuery.length - 1) {
trimmedQuery = trimmedQuery.substring(0, trimmedQuery.length - 1);
}
} else {
trimmedQuery = query;
}
filteredHints = filterWithQuery(hints, MAX_DISPLAYED_HINTS);
formattedHints = formatHints(filteredHints, trimmedQuery);
return {
hints: formattedHints,
match: null, // the CodeHintManager should not format the results
selectInitial: true
};
}
/**
* @constructor
*/
function JSHints() {
}
/**
* Determine whether hints are available for a given editor context
*/
JSHints.prototype.hasHints = function (editor, key) {
if ((key === null) || HintUtils.maybeIdentifier(key)) {
var cursor = session.getCursor(),
token = session.getToken(cursor);
// don't autocomplete within strings or comments, etc.
if (token && HintUtils.hintable(token)) {
var offset = session.getOffset();
// 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 ||
cachedLine !== cursor.line ||
ScopeManager.isScopeDirty(session.editor.document) ||
!cachedScope.containsPositionImmediate(offset)) {
cachedScope = null;
cachedLine = null;
cachedHints = null;
}
return true;
}
}
return false;
};
/**
* Return a list of hints, possibly deferred, for the current editor
* context
*/
JSHints.prototype.getHints = function (key) {
var cursor = session.getCursor(),
token = session.getToken(cursor);
if ((key === null) || HintUtils.maybeIdentifier(token.string)) {
if (token && HintUtils.hintable(token)) {
if (!cachedScope) {
var offset = session.getOffset(),
scopeResponse = ScopeManager.getScopeInfo(session.editor.document, offset),
self = this;
if (scopeResponse.hasOwnProperty("promise")) {
var $deferredHints = $.Deferred();
scopeResponse.promise.done(function (scopeInfo) {
session.setScopeInfo(scopeInfo);
cachedScope = scopeInfo.scope;
cachedLine = cursor.line;
cachedType = session.getType();
cachedHints = session.getHints();
$(self).triggerHandler("resolvedResponse", [cachedHints, cachedType]);
if ($deferredHints.state() === "pending") {
var query = session.getQuery(),
hintResponse = getHintResponse(cachedHints, query);
$deferredHints.resolveWith(null, [hintResponse]);
$(self).triggerHandler("hintResponse", [query]);
}
}).fail(function () {
if ($deferredHints.state() === "pending") {
$deferredHints.reject();
}
});
$(this).triggerHandler("deferredResponse");
return $deferredHints;
} else {
session.setScopeInfo(scopeResponse);
cachedScope = scopeResponse.scope;
cachedLine = cursor.line;
}
}
if (cachedScope) {
var type = session.getType(),
query = session.getQuery();
// Compute fresh hints if none exist, or if the session
// type has changed since the last hint computation
if (!cachedHints ||
type.property !== cachedType.property ||
type.context !== cachedType.context) {
cachedType = type;
cachedHints = session.getHints();
}
return getHintResponse(cachedHints, query);
}
}
}
return null;
};
/**
* Enters the code completion text into the editor
*
* @param {string} hint - text to insert into current code editor
*/
JSHints.prototype.insertHint = function ($hintObj) {
var hint = $hintObj.data("token"),
completion = hint.value,
cursor = session.getCursor(),
token = session.getToken(cursor),
query = session.getQuery(),
start = {line: cursor.line, ch: cursor.ch - query.length},
end = {line: cursor.line, ch: (token ? token.end : cursor.ch)},
delimeter;
if (token && token.string === ".") {
var nextCursor = session.getNextCursorOnLine(),
nextToken = nextCursor ? session.getToken(nextCursor) : null;
if (nextToken && // don't replace delimiters, etc.
HintUtils.maybeIdentifier(nextToken.string) &&
HintUtils.hintable(nextToken)) {
end.ch = nextToken.end;
}
}
// If the hint is a string literal, choose a delimiter in which
// to wrap it, preserving the existing delimiter if possible.
if (hint.literal && hint.kind === "string") {
if (token.string.indexOf(HintUtils.DOUBLE_QUOTE) === 0) {
delimeter = HintUtils.DOUBLE_QUOTE;
} else if (token.string.indexOf(HintUtils.SINGLE_QUOTE) === 0) {
delimeter = HintUtils.SINGLE_QUOTE;
} else {
delimeter = hint.delimeter;
}
completion = completion.replace("\\", "\\\\");
completion = completion.replace(delimeter, "\\" + delimeter);
completion = delimeter + completion + delimeter;
}
// Replace the current token with the completion
session.editor.document.replaceRange(completion, start, end);
// Return false to indicate that another hinting session is not needed
return false;
};
// load the extension
AppInit.appReady(function () {
/*
* When the editor is changed, reset the hinting session and cached
* information, and reject any pending deferred requests.
*/
function initializeSession(editor) {
ScopeManager.handleEditorChange(editor.document);
session = new Session(editor);
cachedScope = null;
cachedLine = null;
cachedHints = null;
cachedType = null;
}
/*
* Install editor change listeners
*/
function installEditorListeners(editor) {
if (!editor) {
return;
}
if (editor.getModeForSelection() === HintUtils.MODE_NAME) {
initializeSession(editor);
$(editor)
.on(HintUtils.eventName("change"), function () {
ScopeManager.handleFileChange(editor.document);
});
}
}
/*
* Uninstall editor change listeners
*/
function uninstallEditorListeners(editor) {
$(editor)
.off(HintUtils.eventName("change"));
}
/*
* Handle the activeEditorChange event fired by EditorManager.
* Uninstalls the change listener on the previous editor
* and installs a change listener on the new editor.
*/
function handleActiveEditorChange(event, current, previous) {
uninstallEditorListeners(previous);
installEditorListeners(current);
}
ExtensionUtils.loadStyleSheet(module, "styles/brackets-js-hints.css");
// uninstall/install change listener as the active editor changes
$(EditorManager)
.on(HintUtils.eventName("activeEditorChange"),
handleActiveEditorChange);
// immediately install the current editor
installEditorListeners(EditorManager.getActiveEditor());
var jsHints = new JSHints();
CodeHintManager.registerHintProvider(jsHints, [HintUtils.MODE_NAME], 0);
// for unit testing
exports.jsHintProvider = jsHints;
exports.initializeSession = initializeSession;
});
});
@@ -0,0 +1,264 @@
/*
* Copyright (c) 2012 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global self, importScripts, setTimeout */
/**
* Loads a file that contains an AMD module definition using the web worker
* importScripts global function.
*
* @param {String} url - The URL of the module to load
*/
function require(url) {
"use strict";
var exports = {};
/*
* The following function is called by AMD modules when loaded with
* importScripts. CommonJS-style modules will only pass a wrapper function
* as a single argument; proper AMD-style modules may additionally pass an
* array of bindings, which are ignored. In the former case, the wrapper
* function expects require, exports and module arguments; in the latter
* case, the wrapper function expects only an exports arguments.
*/
self.define = function (bindings, wrapper) {
var module = { exports: exports },
require = null;
if (typeof bindings === "function") {
wrapper = bindings;
} else {
require = module.exports;
}
wrapper(require, module.exports, module);
exports = module.exports;
};
self.define.amd = true;
importScripts(url);
return exports;
}
(function () {
"use strict";
var Scope = require("Scope.js"),
HintUtils = require('HintUtils.js'),
esprima = require('thirdparty/esprima/esprima.js');
var MAX_RETRIES = 100;
function _log(msg) {
self.postMessage({log: msg });
}
/**
* Walk the scope to find all the objects of a given type, along with a
* list of their positions in the file.
*/
function siftPositions(walk, keyProp) {
var occurrences,
results = [],
key,
token,
comparator = function (a, b) { return a - b; };
occurrences = walk(function (acc, token) {
if (Object.prototype.hasOwnProperty.call(acc, token[keyProp])) {
acc[token[keyProp]].push(token.range[0]);
} else {
acc[token[keyProp]] = [token.range[0]];
}
return acc;
}, {});
for (key in occurrences) {
if (Object.prototype.hasOwnProperty.call(occurrences, key)) {
token = HintUtils.makeToken(key, occurrences[key].sort(comparator));
results.push(token);
}
}
return results;
}
/**
* Walk the scope to compute all available association objects
*/
function siftAssociations(walk) {
return walk(function (acc, assoc) {
var obj = assoc.object,
prop = assoc.property;
if (Object.prototype.hasOwnProperty.call(acc, obj.name)) {
if (Object.prototype.hasOwnProperty.call(acc[obj.name], prop.name)) {
acc[obj.name][prop.name]++;
} else {
acc[obj.name][prop.name] = 1;
}
} else {
acc[obj.name] = {};
acc[obj.name][prop.name] = 1;
}
return acc;
}, {});
}
/**
* Look for a JSLint globals annotation in the comments
*/
function extractGlobals(comments) {
var globals = [];
if (comments) {
comments.forEach(function (c) {
if (c.type === "Block") {
if (c.value) {
if (c.value.indexOf("global") === 0) {
c.value.substring(7).split(",").forEach(function (g) {
var index = g.indexOf(":");
if (index >= 0) {
g = g.substring(0, index);
}
globals.push(HintUtils.makeToken(g.trim()));
});
} else if (c.value.indexOf("jslint") === 0) {
c.value.substring(7).split(",").forEach(function (e) {
var index = e.indexOf(":"),
prop = (index >= 0) ? e.substring(0, index).trim() : "",
val = (index >= 0) ? e.substring(index + 1, e.length).trim() : "";
if (val === "true" && HintUtils.JSL_GLOBAL_DEFS.hasOwnProperty(prop)) {
globals = globals.concat(HintUtils.JSL_GLOBAL_DEFS[prop]);
}
});
}
}
}
});
}
globals.sort(function (a, b) { return a.value < b.value; });
return globals;
}
/**
* Send the scope and associated parse information back to the caller.
*/
function respond(dir, file, length, parseObj) {
var success = !!parseObj,
response = {
type : HintUtils.SCOPE_MSG_TYPE,
dir : dir,
file : file,
length : length,
success : success
};
if (success) {
var scope = parseObj.scope,
globals = parseObj.globals,
identifiers = siftPositions(scope.walkDownIdentifiers.bind(scope), "name"),
properties = siftPositions(scope.walkDownProperties.bind(scope), "name"),
literals = siftPositions(scope.walkDownLiterals.bind(scope), "value"),
associations = siftAssociations(scope.walkDownAssociations.bind(scope));
response.scope = scope;
response.globals = HintUtils.annotateGlobals(globals);
response.identifiers = identifiers;
response.properties = HintUtils.annotateWithPath(properties, dir, file);
response.literals = HintUtils.annotateLiterals(literals, "string");
response.associations = associations;
}
self.postMessage(response);
}
/**
* Use Esprima to parse a JavaScript text
*/
function parse(dir, file, text, retries) {
try {
var ast = esprima.parse(text, {
range : true,
tolerant : true,
comment : true
});
respond(dir, file, text.length, {
scope : new Scope(ast),
globals : extractGlobals(ast.comments)
});
} catch (err) {
// If parsing fails, we can try again after blanking out the line
// that caused the parse error. This is unreliable though, because
// the line number on which the parser fails is not necessarily the
// best line to remove. Some errors will cause the entire remainder
// of the file to be blanked out, never resulting in a parseable
// file. Consequently, this is attempted only when necessary; i.e.,
// when the request.force flag is set.
// Inspired by fuckit.js: https://github.com/mattdiamond/fuckitjs
// _log("Parsing failed: " + err + " at " + err.index);
if (retries > 0) {
var lines = text.split("\n"),
lineno = Math.min(lines.length, err.lineNumber) - 1,
newline,
removed;
// Blank the offending line and start over
if (-1 < lineno < lines.length) {
newline = lines[lineno].replace(/./g, " ");
if (newline !== lines[lineno]) {
removed = lines.splice(lineno, 1, newline);
if (removed && removed.length > 0) {
setTimeout(function () {
parse(dir, file, text.length, lines.join("\n"), --retries);
}, 0);
return;
}
}
}
}
respond(dir, file, text.length, null);
}
}
self.addEventListener("message", function (e) {
var request = e.data,
type = request.type;
if (type === HintUtils.SCOPE_MSG_TYPE) {
var dir = request.dir,
file = request.file,
text = request.text,
retries = request.force ? MAX_RETRIES : 0;
setTimeout(function () { parse(dir, file, text, retries); }, 0);
} else {
_log("Unknown message: " + JSON.stringify(request));
}
});
}());
@@ -0,0 +1,56 @@
/*
* Copyright (c) 2012 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.
*
*/
.brackets-js-hints.priority-high {
color: rgb(0, 100, 0); /* green */
}
.brackets-js-hints.priority-medium {
color: rgb(125, 125, 0); /* yellow */
}
.brackets-js-hints.priority-low {
color: rgb(0, 0, 100); /* blue */
}
.brackets-js-hints.variable-hint {
}
.brackets-js-hints.property-hint {
}
.brackets-js-hints.global-hint {
font-style: italic;
}
.brackets-js-hints.literal-hint {
color: rgb(50, 50, 50); /* dark grey */
}
.brackets-js-hints.keyword-hint {
font-family: monospace;
}
.brackets-js-hints .matched-hint {
font-weight: bold;
}
@@ -0,0 +1,23 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global brackets, $ */
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!");
}
}
@@ -0,0 +1,14 @@
/*jslint vars: true, plusplus: true, devel: true, rhino: true, nomen: true, indent: 4, maxerr: 50 */
/*global crazyGlobal, anotherCrazyGlobal */
var D1 = { propD : 1 },
D2 = { propD : 2 };
function funE(paramE1, paramE2) {
'use strict';
var E1 = { propE : 1 },
E2 = { propE : 2 };
console.log("a very nice string");
}
@@ -0,0 +1,19 @@
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,462 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, describe, it, xit, expect, beforeEach, afterEach, waitsFor, runs, $, brackets, waitsForDone */
define(function (require, exports, module) {
"use strict";
var Editor = brackets.getModule("editor/Editor").Editor,
EditorManager = brackets.getModule("editor/EditorManager"),
FileUtils = brackets.getModule("file/FileUtils"),
DocumentManager = brackets.getModule("document/DocumentManager"),
SpecRunnerUtils = brackets.getModule("spec/SpecRunnerUtils"),
UnitTestReporter = brackets.getModule("test/UnitTestReporter"),
JSCodeHints = require("main");
var extensionPath = FileUtils.getNativeModuleDirectoryPath(module),
testPath = extensionPath + "/test/file1.js",
testDoc = null,
testEditor;
/**
* Returns an Editor suitable for use in isolation: i.e., a Document that
* will never be set as the currentDocument or added to the working set.
* @return {!Editor}
*/
function createMockEditor(doc, mode, visibleRange) {
mode = mode || "";
// Initialize EditorManager
var $editorHolder = $("<div id='mock-editor-holder'/>");
EditorManager.setEditorHolder($editorHolder);
EditorManager._init();
$("body").append($editorHolder);
// create Editor instance
var editor = new Editor(doc, true, mode, $editorHolder.get(0), visibleRange);
return editor;
}
describe("JavaScript Code Hinting", function () {
// Ask provider for hints at current cursor position; expect it to return some
function expectHints(provider, key) {
if (key === undefined) {
key = null;
}
expect(provider.hasHints(testEditor, key)).toBe(true);
return provider.getHints(null);
}
// Ask provider for hints at current cursor position; expect it NOT to return any
function expectNoHints(provider, key) {
if (key === undefined) {
key = null;
}
expect(provider.hasHints(testEditor, key)).toBe(false);
}
function _indexOf(hintList, hint) {
var index = -1,
counter = 0;
for (counter; counter < hintList.length; counter++) {
if (hintList[counter].data("token").value === hint) {
index = counter;
break;
}
}
return index;
}
function _waitForHints(hintObj, callback) {
var complete = false,
hintList = null;
if (hintObj.hasOwnProperty("hints")) {
complete = true;
hintList = hintObj.hints;
} else {
hintObj.done(function (obj) {
complete = true;
hintList = obj.hints;
});
}
waitsFor(function () {
return complete;
}, "Expected hints did not resolve", 3000);
runs(function () { callback(hintList); });
}
function hintsAbsent(hintObj, expectedHints) {
_waitForHints(hintObj, function (hintList) {
expect(hintList).not.toBeNull();
expectedHints.forEach(function (expectedHint) {
expect(_indexOf(hintList, expectedHint)).toBe(-1);
});
});
}
function hintsPresent(hintObj, expectedHints) {
_waitForHints(hintObj, function (hintList) {
expect(hintList).not.toBeNull();
expectedHints.forEach(function (expectedHint) {
expect(_indexOf(hintList, expectedHint)).not.toBe(-1);
});
});
}
function hintsPresentOrdered(hintObj, expectedHints) {
var prevIndex = -1,
currIndex;
_waitForHints(hintObj, function (hintList) {
expect(hintList).not.toBeNull();
expectedHints.forEach(function (expectedHint) {
currIndex = _indexOf(hintList, expectedHint);
expect(currIndex).toBeGreaterThan(prevIndex);
prevIndex = currIndex;
});
});
}
function hintsPresentExact(hintObj, expectedHints) {
_waitForHints(hintObj, function (hintList) {
expect(hintList).not.toBeNull();
expectedHints.forEach(function (expectedHint, index) {
expect(hintList[index].data("token").value).toBe(expectedHint);
});
});
}
function selectHint(provider, hintObj, index) {
var hintList = expectHints(provider);
_waitForHints(hintObj, function (hintList) {
expect(hintList).not.toBeNull();
expect(hintList[index].data("token")).not.toBeNull();
expect(provider.insertHint(hintList[index])).toBe(false);
});
}
describe("JavaScript Code Hinting", 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, "javascript");
JSCodeHints.initializeSession(testEditor);
});
});
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;
});
it("should list declared variable and function names in outer scope", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresentExact(hintObj, ["A2", "A3", "funB", "A1"]);
});
it("should filter hints by query", function () {
testEditor.setCursorPos({ line: 5, ch: 10 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresentExact(hintObj, ["A2", "A3", "A1"]);
hintsAbsent(hintObj, ["funB"]);
});
it("should list keywords", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresent(hintObj, ["function", "var", "switch"]);
});
it("should list explicitly defined globals from JSLint annotations", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresent(hintObj, ["brackets", "$"]);
});
it("should list implicitly defined globals from JSLint annotations", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresent(hintObj, ["alert", "console", "confirm", "navigator", "window", "frames"]);
});
it("should NOT list implicitly defined globals from missing JSLint annotations", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["ActiveXObject", "CScript", "VBArray"]);
});
it("should NOT list explicitly defined globals from JSLint annotations in other files", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["crazyGlobal", "anotherCrazyGlobal"]);
});
it("should NOT list implicitly defined globals from JSLint annotations in other files", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["spawn", "version", "toint32"]);
});
it("should list literal constants", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresent(hintObj, ["null", "undefined", "true", "false"]);
});
it("should NOT list variables, function names and parameter names out of scope", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["paramB2", "paramB1"]);
});
it("should NOT list variables, function names and parameter names in other files", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["D1", "D2", "funE", "E1", "E2"]);
});
it("should NOT property names on value lookups", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["propA", "propB", "propC"]);
});
it("should list declared variable, function and parameter names in inner scope", function () {
testEditor.setCursorPos({ line: 12, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresentExact(hintObj, ["funC", "B2", "B1", "paramB2", "paramB1", "funB", "A2", "A3", "A1"]);
});
it("should list string literals that occur in the file", function () {
testEditor.setCursorPos({ line: 12, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresent(hintObj, ["use strict"]);
});
it("should NOT list string literals that other files", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["a very nice string"]);
});
it("should list property names that occur in the file", function () {
testEditor.setCursorPos({ line: 17, ch: 11 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresent(hintObj, ["propA", "propB", "propC"]);
});
it("should list property names that occur in other files", function () {
testEditor.setCursorPos({ line: 17, ch: 11 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresent(hintObj, ["propD", "propE"]);
});
it("should NOT list variable, parameter or function names on property lookups", function () {
testEditor.setCursorPos({ line: 17, ch: 11 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["A1", "A2", "funB", "paramB1", "paramB2", "B1", "B2", "funC", "paramC1", "paramC2"]);
});
it("should NOT list keywords on property lookups", function () {
testEditor.setCursorPos({ line: 17, ch: 11 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsAbsent(hintObj, ["case", "function", "var"]);
});
it("should NOT list implicit hints on left-brace", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
expectNoHints(JSCodeHints.jsHintProvider, "{");
});
it("should list implicit hints when typing variable names", function () {
testEditor.setCursorPos({ line: 6, ch: 0 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresentExact(hintObj, ["A2", "A3", "funB", "A1"]);
});
it("should list implicit hints when typing property lookups", function () {
testEditor.setCursorPos({ line: 17, ch: 10 });
expectHints(JSCodeHints.jsHintProvider, ".");
});
it("should list implicit hints when typing string literals (single quote)", function () {
testEditor.setCursorPos({ line: 9, ch: 0 });
expectHints(JSCodeHints.jsHintProvider, "'");
});
it("should list implicit hints when typing string literals (double quote)", function () {
testEditor.setCursorPos({ line: 9, ch: 0 });
expectHints(JSCodeHints.jsHintProvider, "\"");
});
it("should give priority to property names with associated with the current context", function () {
testEditor.setCursorPos({ line: 19, ch: 11 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresentOrdered(hintObj, ["propB", "propA"]);
hintsPresentOrdered(hintObj, ["propB", "propC"]);
});
it("should give priority to property names with associated with the current context from other files", function () {
testEditor.setCursorPos({ line: 20, ch: 16 });
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresentOrdered(hintObj, ["log", "propA"]);
hintsPresentOrdered(hintObj, ["log", "propB"]);
hintsPresentOrdered(hintObj, ["log", "propC"]);
hintsPresentOrdered(hintObj, ["log", "propD"]);
hintsPresentOrdered(hintObj, ["log", "propE"]);
});
it("should choose the correct delimiter for string literal hints with no query", function () {
var start = { line: 18, ch: 0 },
end = { line: 18, ch: 18 };
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, 13); // hint 13 is "hello\\\"world!"
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, end)).toEqual('"hello\\\\\\" world!"');
});
});
it("should insert value hints with no current query", function () {
var start = { line: 6, ch: 0 },
end = { line: 6, ch: 4 };
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, 2); // hint 2 is "funB"
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, end)).toEqual("funB");
});
});
it("should insert value hints replacing the current query", function () {
var start = { line: 5, ch: 10 }, // A3 = A<here>2;
before = { line: 5, ch: 9 },
end = { line: 5, ch: 11 };
testEditor.setCursorPos(start);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresentExact(hintObj, ["A2", "A3", "A1"]);
selectHint(JSCodeHints.jsHintProvider, hintObj, 2); // hint 2 is "A1"
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(before, end)).toEqual("A1");
});
});
it("should insert property hints with no current query", function () {
var start = { line: 6, ch: 0 },
middle = { line: 6, ch: 3 },
end = { line: 6, ch: 8 };
testDoc.replaceRange("A1.", start, start);
testEditor.setCursorPos(middle);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, 0); // hint 0 is "propA"
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, end)).toEqual("A1.propA");
expect(testDoc.getLine(end.line).length).toEqual(8);
});
});
it("should replace property hints with no current query", function () {
var start = { line: 6, ch: 0 },
middle = { line: 6, ch: 3 },
end = { line: 6, ch: 8 };
testDoc.replaceRange("A1.prop", start, start);
testEditor.setCursorPos(middle);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, 0); // hint 0 is "propA"
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, end)).toEqual("A1.propA");
expect(testDoc.getLine(end.line).length).toEqual(8);
});
});
it("should replace property hints with a partial current query", function () {
var start = { line: 6, ch: 0 },
middle = { line: 6, ch: 6 },
end = { line: 6, ch: 8 };
testDoc.replaceRange("A1.pro", start, start);
testEditor.setCursorPos(middle);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, 0); // hint 0 is "propA"
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, end)).toEqual("A1.propA");
expect(testDoc.getLine(end.line).length).toEqual(8);
});
});
it("should replace property hints replacing a partial current query", function () {
var start = { line: 6, ch: 0 },
middle = { line: 6, ch: 6 },
end = { line: 6, ch: 8 };
testDoc.replaceRange("A1.propB", start, start);
testEditor.setCursorPos(middle);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, 0); // hint 0 is "propA"
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, end)).toEqual("A1.propA");
expect(testDoc.getLine(end.line).length).toEqual(8);
});
});
it("should replace property hints but not following delimiters", function () {
var start = { line: 6, ch: 0 },
middle = { line: 6, ch: 4 },
end = { line: 6, ch: 9 },
endplus = { line: 6, ch: 10 };
testDoc.replaceRange("(A1.prop)", start, start);
testEditor.setCursorPos(middle);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
selectHint(JSCodeHints.jsHintProvider, hintObj, 0); // hint 0 is "propA"
runs(function () {
expect(testEditor.getCursorPos()).toEqual(end);
expect(testDoc.getRange(start, endplus)).toEqual("(A1.propA)");
expect(testDoc.getLine(endplus.line).length).toEqual(10);
});
});
});
});
});