1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2025-03-13 23:18:09 +00:00

Esprima update

This commit is contained in:
Jeremy Ruston 2012-05-07 09:43:29 +01:00
parent 3b2fcc83e7
commit ac50352877
30 changed files with 10934 additions and 7544 deletions

8
node_modules/esprima/README.md generated vendored
View File

@ -3,6 +3,14 @@ Esprima ([esprima.org](http://esprima.org)) is an educational
(also popularly known as [JavaScript](http://en.wikipedia.org/wiki/JavaScript>JavaScript))
parsing infrastructure for multipurpose analysis. It is also written in ECMAScript.
Esprima serves as a good basis for various tools such as source
modification ([Esmorph](https://github.com/ariya/esmorph)), coverage analyzer
([node-cover](https://github.com/itay/node-cover) and
[coveraje](https://github.com/coveraje/coveraje)),
source-to-source compiler ([Marv](https://github.com/Yoric/Marv-the-Tinker)),
syntax formatter ([Code Painter](https://github.com/fawek/codepainter)),
and code generator ([escodegen](https://github.com/Constellation/escodegen)).
Esprima can be used in a web browser:
<script src="esprima.js"></script>

View File

@ -9,6 +9,7 @@
/* This is needed to prevent an IE[67] bug where the scrolled content
is visible outside of the scrolling box. */
position: relative;
outline: none;
}
.CodeMirror-gutter {
@ -27,6 +28,7 @@
}
.CodeMirror-lines {
padding: .4em;
white-space: pre;
}
.CodeMirror pre {
@ -59,7 +61,10 @@
position: absolute;
visibility: hidden;
border-left: 1px solid black;
border-right:none;
width:0;
}
.CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {}
.CodeMirror-focused pre.CodeMirror-cursor {
visibility: visible;
}

View File

@ -1,4 +1,4 @@
// CodeMirror version 2.21
// CodeMirror version 2.23
//
// All functions that need access to the editor's state live inside
// the CodeMirror function. Below that, at the bottom of the file,
@ -6,7 +6,7 @@
// CodeMirror is the only global var we claim
var CodeMirror = (function() {
// This is the function that produces an editor instance. It's
// This is the function that produces an editor instance. Its
// closure is used to store the editor state.
function CodeMirror(place, givenOptions) {
// Determine effective options based on given values and defaults.
@ -15,9 +15,8 @@ var CodeMirror = (function() {
if (defaults.hasOwnProperty(opt))
options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
var targetDocument = options["document"];
// The element in which the editor lives.
var wrapper = targetDocument.createElement("div");
var wrapper = document.createElement("div");
wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "");
// This mess creates the base DOM structure for the editor.
wrapper.innerHTML =
@ -30,7 +29,7 @@ var CodeMirror = (function() {
'<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
// Provides positioning relative to (visible) text origin
'<div class="CodeMirror-lines"><div style="position: relative; z-index: 0">' +
'<div style="position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden; outline: 5px auto none"></div>' +
'<div style="position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden;"></div>' +
'<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
'<div style="position: relative; z-index: -1"></div><div></div>' + // DIVs containing the selection and the actual code
'</div></div></div></div></div>';
@ -48,7 +47,10 @@ var CodeMirror = (function() {
if (!webkit) lineSpace.draggable = true;
lineSpace.style.outline = "none";
if (options.tabindex != null) input.tabIndex = options.tabindex;
if (options.autofocus) focusInput();
if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
// Needed to handle Tab key in KHTML
if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute";
// Check for problem with IE innerHTML not working when we have a
// P (or similar) parent node.
@ -81,12 +83,13 @@ var CodeMirror = (function() {
gutterDirty, callbacks;
// Current visible range (may be bigger than the view window).
var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
// bracketHighlighted is used to remember that a backet has been
// bracketHighlighted is used to remember that a bracket has been
// marked.
var bracketHighlighted;
// Tracks the maximum line length so that the horizontal scrollbar
// can be kept static when scrolling.
var maxLine = "", maxWidth, tabText = computeTabText();
var maxLine = "", maxWidth;
var tabCache = {};
// Initialize the content.
operation(function(){setValue(options.value || ""); updateInput = false;})();
@ -124,10 +127,16 @@ var CodeMirror = (function() {
if (!options.readOnly) replaceSelection("");
}));
// Needed to handle Tab key in KHTML
if (khtml) connect(code, "mouseup", function() {
if (document.activeElement == input) input.blur();
focusInput();
});
// IE throws unspecified error in certain cases, when
// trying to access activeElement before onload
var hasFocus; try { hasFocus = (targetDocument.activeElement == input); } catch(e) { }
if (hasFocus) setTimeout(onFocus, 20);
var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { }
if (hasFocus || options.autofocus) setTimeout(onFocus, 20);
else onBlur();
function isLine(l) {return l >= 0 && l < doc.size;}
@ -141,7 +150,7 @@ var CodeMirror = (function() {
setValue: operation(setValue),
getSelection: getSelection,
replaceSelection: operation(replaceSelection),
focus: function(){focusInput(); onFocus(); fastPoll();},
focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();},
setOption: function(option, value) {
var oldVal = options[option];
options[option] = value;
@ -150,9 +159,11 @@ var CodeMirror = (function() {
else if (option == "readOnly" && !value) {resetInput(true);}
else if (option == "theme") themeChanged();
else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)();
else if (option == "tabSize") operation(tabsChanged)();
if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme")
else if (option == "tabSize") updateDisplay(true);
if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme") {
gutterChanged();
updateDisplay(true);
}
},
getOption: function(option) {return options[option];},
undo: operation(undo),
@ -176,17 +187,23 @@ var CodeMirror = (function() {
line = clipLine(line == null ? doc.size - 1: line);
return getStateBefore(line + 1);
},
cursorCoords: function(start){
cursorCoords: function(start, mode) {
if (start == null) start = sel.inverted;
return pageCoords(start ? sel.from : sel.to);
return this.charCoords(start ? sel.from : sel.to, mode);
},
charCoords: function(pos, mode) {
pos = clipPos(pos);
if (mode == "local") return localCoords(pos, false);
if (mode == "div") return localCoords(pos, true);
return pageCoords(pos);
},
charCoords: function(pos){return pageCoords(clipPos(pos));},
coordsChar: function(coords) {
var off = eltOffset(lineSpace);
return coordsChar(coords.x - off.left, coords.y - off.top);
},
markText: operation(markText),
setBookmark: setBookmark,
findMarksAt: findMarksAt,
setMarker: operation(addGutterMarker),
clearMarker: operation(removeGutterMarker),
setLineClass: operation(setLineClass),
@ -254,12 +271,21 @@ var CodeMirror = (function() {
replaceRange: operation(replaceRange),
getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
triggerOnKeyDown: operation(onKeyDown),
execCommand: function(cmd) {return commands[cmd](instance);},
// Stuff used by commands, probably not much use to outside code.
moveH: operation(moveH),
deleteH: operation(deleteH),
moveV: operation(moveV),
toggleOverwrite: function() {overwrite = !overwrite;},
toggleOverwrite: function() {
if(overwrite){
overwrite = false;
cursor.className = cursor.className.replace(" CodeMirror-overwrite", "");
} else {
overwrite = true;
cursor.className += " CodeMirror-overwrite";
}
},
posFromIndex: function(off) {
var lineNo = 0, ch;
@ -280,8 +306,8 @@ var CodeMirror = (function() {
return index;
},
scrollTo: function(x, y) {
if (x != null) scroller.scrollTop = x;
if (y != null) scroller.scrollLeft = y;
if (x != null) scroller.scrollLeft = x;
if (y != null) scroller.scrollTop = y;
updateDisplay([]);
},
@ -363,7 +389,7 @@ var CodeMirror = (function() {
!posLess(start, sel.from) && !posLess(sel.to, start)) {
// Let the drag handler handle this.
if (webkit) lineSpace.draggable = true;
var up = connect(targetDocument, "mouseup", operation(function(e2) {
var up = connect(document, "mouseup", operation(function(e2) {
if (webkit) lineSpace.draggable = false;
draggingText = false;
up();
@ -374,6 +400,8 @@ var CodeMirror = (function() {
}
}), true);
draggingText = true;
// IE's approach to draggable
if (lineSpace.dragDrop) lineSpace.dragDrop();
return;
}
e_preventDefault(e);
@ -392,12 +420,7 @@ var CodeMirror = (function() {
}
}
var move = connect(targetDocument, "mousemove", operation(function(e) {
clearTimeout(going);
e_preventDefault(e);
extend(e);
}), true);
var up = connect(targetDocument, "mouseup", operation(function(e) {
function done(e) {
clearTimeout(going);
var cur = posFromMouse(e);
if (cur) setSelectionUser(start, cur);
@ -405,7 +428,14 @@ var CodeMirror = (function() {
focusInput();
updateInput = true;
move(); up();
}
var move = connect(document, "mousemove", operation(function(e) {
clearTimeout(going);
e_preventDefault(e);
if (!ie && !e_button(e)) done(e);
else extend(e);
}), true);
var up = connect(document, "mouseup", operation(done), true);
}
function onDoubleClick(e) {
for (var n = e_target(e); n != wrapper; n = n.parentNode)
@ -454,51 +484,78 @@ var CodeMirror = (function() {
}
function onDragStart(e) {
var txt = getSelection();
// This will reset escapeElement
htmlEscape(txt);
e.dataTransfer.setDragImage(escapeElement, 0, 0);
e.dataTransfer.setData("Text", txt);
// Use dummy image instead of default browsers image.
if (gecko || chrome) {
var img = document.createElement('img');
img.scr = 'data:image/gif;base64,R0lGODdhAgACAIAAAAAAAP///ywAAAAAAgACAAACAoRRADs='; //1x1 image
e.dataTransfer.setDragImage(img, 0, 0);
}
}
function handleKeyBinding(e) {
var name = keyNames[e_prop(e, "keyCode")], next = keyMap[options.keyMap].auto, bound, dropShift;
function handleNext() {
return next.call ? next.call(null, instance) : next;
}
if (name == null || e.altGraphKey) {
if (next) options.keyMap = handleNext();
return null;
}
if (e_prop(e, "altKey")) name = "Alt-" + name;
if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name;
if (e_prop(e, "metaKey")) name = "Cmd-" + name;
if (e_prop(e, "shiftKey") &&
(bound = lookupKey("Shift-" + name, options.extraKeys, options.keyMap))) {
dropShift = true;
} else {
bound = lookupKey(name, options.extraKeys, options.keyMap);
}
function doHandleBinding(bound, dropShift) {
if (typeof bound == "string") {
if (commands.propertyIsEnumerable(bound)) bound = commands[bound];
else bound = null;
bound = commands[bound];
if (!bound) return false;
}
if (next && (bound || !isModifierKey(e))) options.keyMap = handleNext();
if (!bound) return false;
var prevShift = shiftSelecting;
try {
if (options.readOnly) suppressEdits = true;
if (dropShift) shiftSelecting = null;
bound(instance);
} catch(e) {
if (e != Pass) throw e;
return false;
} finally {
shiftSelecting = prevShift;
suppressEdits = false;
}
e_preventDefault(e);
return true;
}
var lastStoppedKey = null;
function handleKeyBinding(e) {
// Handle auto keymap transitions
var startMap = getKeyMap(options.keyMap), next = startMap.auto;
clearTimeout(maybeTransition);
if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
if (getKeyMap(options.keyMap) == startMap) {
options.keyMap = (next.call ? next.call(null, instance) : next);
}
}, 50);
var name = keyNames[e_prop(e, "keyCode")], handled = false;
if (name == null || e.altGraphKey) return false;
if (e_prop(e, "altKey")) name = "Alt-" + name;
if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name;
if (e_prop(e, "metaKey")) name = "Cmd-" + name;
if (e_prop(e, "shiftKey")) {
handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap,
function(b) {return doHandleBinding(b, true);})
|| lookupKey(name, options.extraKeys, options.keyMap, function(b) {
if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b);
});
} else {
handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding);
}
if (handled) {
e_preventDefault(e);
if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
}
return handled;
}
function handleCharBinding(e, ch) {
var handled = lookupKey("'" + ch + "'", options.extraKeys,
options.keyMap, doHandleBinding);
if (handled) e_preventDefault(e);
return handled;
}
var lastStoppedKey = null, maybeTransition;
function onKeyDown(e) {
if (!focused) onFocus();
if (ie && e.keyCode == 27) { e.returnValue = false; }
if (pollingFast) { if (readInput()) pollingFast = false; }
if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
var code = e_prop(e, "keyCode");
// IE does strange things with escape.
@ -513,15 +570,17 @@ var CodeMirror = (function() {
}
}
function onKeyPress(e) {
if (pollingFast) readInput();
if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
if (window.opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
if (window.opera && !e.which && handleKeyBinding(e)) return;
if (((window.opera && !e.which) || khtml) && handleKeyBinding(e)) return;
var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) {
var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
if (mode.electricChars.indexOf(ch) > -1)
setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75);
}
if (handleCharBinding(e, ch)) return;
fastPoll();
}
function onKeyUp(e) {
@ -567,9 +626,10 @@ var CodeMirror = (function() {
}
updateLinesNoUndo(from, to, newText, selFrom, selTo);
}
function unredoHelper(from, to, dir) {
var set = from.pop(), len = set ? set.length : 0, out = [];
for (var i = dir > 0 ? 0 : len - 1, e = dir > 0 ? len : -1; i != e; i += dir) {
function unredoHelper(from, to) {
if (!from.length) return;
var set = from.pop(), out = [];
for (var i = set.length - 1; i >= 0; i -= 1) {
var change = set[i];
var replaced = [], end = change.start + change.added;
doc.iter(change.start, end, function(line) { replaced.push(line.text); });
@ -581,8 +641,8 @@ var CodeMirror = (function() {
updateInput = true;
to.push(out);
}
function undo() {unredoHelper(history.done, history.undone, -1);}
function redo() {unredoHelper(history.undone, history.done, 1);}
function undo() {unredoHelper(history.done, history.undone);}
function redo() {unredoHelper(history.undone, history.done);}
function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
if (suppressEdits) return;
@ -784,7 +844,7 @@ var CodeMirror = (function() {
if (!posEq(sel.from, sel.to)) {
prevInput = "";
input.value = getSelection();
input.select();
selectInput(input);
} else if (user) prevInput = input.value = "";
}
@ -806,11 +866,11 @@ var CodeMirror = (function() {
return scrollIntoView(x, cursor.y, x, cursor.yBot);
}
function scrollIntoView(x1, y1, x2, y2) {
var pl = paddingLeft(), pt = paddingTop(), lh = textHeight();
var pl = paddingLeft(), pt = paddingTop();
y1 += pt; y2 += pt; x1 += pl; x2 += pl;
var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1 - 2*lh); scrolled = true;}
else if (y2 > screentop + screen) {scroller.scrollTop = y2 + lh - screen; scrolled = true;}
if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1); scrolled = true;}
else if (y2 > screentop + screen) {scroller.scrollTop = y2 - screen; scrolled = true;}
var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
@ -890,7 +950,7 @@ var CodeMirror = (function() {
throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) +
" nodes=" + lineDiv.childNodes.length);
if (options.lineWrapping) {
function checkHeights() {
maxWidth = scroller.clientWidth;
var curNode = lineDiv.firstChild, heightChanged = false;
doc.iter(showingFrom, showingTo, function(line) {
@ -905,6 +965,11 @@ var CodeMirror = (function() {
});
if (heightChanged)
code.style.height = (doc.height * th + 2 * paddingTop()) + "px";
return heightChanged;
}
if (options.lineWrapping) {
checkHeights();
} else {
if (maxWidth == null) maxWidth = stringWidth(maxLine);
if (maxWidth > scroller.clientWidth) {
@ -916,8 +981,12 @@ var CodeMirror = (function() {
lineSpace.style.width = code.style.width = "";
}
}
gutter.style.display = gutterDisplay;
if (different || gutterDirty) updateGutter();
if (different || gutterDirty) {
// If the gutter grew in size, re-check heights. If those changed, re-draw gutter.
updateGutter() && options.lineWrapping && checkHeights() && updateGutter();
}
updateSelection();
if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
return true;
@ -965,16 +1034,17 @@ var CodeMirror = (function() {
}
// This pass fills in the lines that actually changed.
var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
var scratch = targetDocument.createElement("div"), newElt;
var scratch = document.createElement("div");
doc.iter(from, to, function(line) {
if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
if (!nextIntact || nextIntact.from > j) {
if (line.hidden) var html = scratch.innerHTML = "<pre></pre>";
else {
var html = '<pre>' + line.getHTML(tabText) + '</pre>';
var html = '<pre' + (line.className ? ' class="' + line.className + '"' : '') + '>'
+ line.getHTML(makeTab) + '</pre>';
// Kludge to make sure the styled element lies behind the selection (by z-index)
if (line.className)
html = '<div style="position: relative"><pre class="' + line.className +
if (line.bgClassName)
html = '<div style="position: relative"><pre class="' + line.bgClassName +
'" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2">&#160;</pre>' + html + "</div>";
}
scratch.innerHTML = html;
@ -990,7 +1060,7 @@ var CodeMirror = (function() {
if (!options.gutter && !options.lineNumbers) return;
var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
var html = [], i = showingFrom;
var html = [], i = showingFrom, normalNode;
doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
if (line.hidden) {
html.push("<pre></pre>");
@ -1004,17 +1074,24 @@ var CodeMirror = (function() {
html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text);
for (var j = 1; j < line.height; ++j) html.push("<br/>&#160;");
html.push("</pre>");
if (!marker) normalNode = i;
}
++i;
});
gutter.style.display = "none";
gutterText.innerHTML = html.join("");
var minwidth = String(doc.size).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = "";
while (val.length + pad.length < minwidth) pad += "\u00a0";
if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild);
// Make sure scrolling doesn't cause number gutter size to pop
if (normalNode != null) {
var node = gutterText.childNodes[normalNode - showingFrom];
var minwidth = String(doc.size).length, val = eltText(node), pad = "";
while (val.length + pad.length < minwidth) pad += "\u00a0";
if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild);
}
gutter.style.display = "";
var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2;
lineSpace.style.marginLeft = gutter.offsetWidth + "px";
gutterDirty = false;
return resized;
}
function updateSelection() {
var collapsed = posEq(sel.from, sel.to);
@ -1035,16 +1112,18 @@ var CodeMirror = (function() {
html += '<div class="CodeMirror-selected" style="position: absolute; left: ' + left +
'px; top: ' + top + 'px; right: ' + right + 'px; height: ' + height + 'px"></div>';
}
var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth;
var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight;
if (sel.from.ch && fromPos.y >= 0) {
var right = sameLine ? lineSpace.clientWidth - toPos.x : 0;
var right = sameLine ? clientWidth - toPos.x : 0;
add(fromPos.x, fromPos.y, right, th);
}
var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0));
var middleHeight = Math.min(toPos.y, lineSpace.clientHeight) - middleStart;
var middleHeight = Math.min(toPos.y, clientHeight) - middleStart;
if (middleHeight > 0.2 * th)
add(0, middleStart, 0, middleHeight);
if ((!sameLine || !sel.from.ch) && toPos.y < lineSpace.clientHeight - .5 * th)
add(0, toPos.y, lineSpace.clientWidth - toPos.x, th);
if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th)
add(0, toPos.y, clientWidth - toPos.x, th);
selectionDiv.innerHTML = html;
cursor.style.display = "none";
selectionDiv.style.display = "";
@ -1074,13 +1153,32 @@ var CodeMirror = (function() {
if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
// Skip over hidden lines.
if (from.line != oldFrom) from = skipHidden(from, oldFrom, sel.from.ch);
if (from.line != oldFrom) {
var from1 = skipHidden(from, oldFrom, sel.from.ch);
// If there is no non-hidden line left, force visibility on current line
if (!from1) setLineHidden(from.line, false);
else from = from1;
}
if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
if (posEq(from, to)) sel.inverted = false;
else if (posEq(from, sel.to)) sel.inverted = false;
else if (posEq(to, sel.from)) sel.inverted = true;
if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
var head = sel.inverted ? from : to;
if (head.line != sel.from.line && sel.from.line < doc.size) {
var oldLine = getLine(sel.from.line);
if (/^\s+$/.test(oldLine.text))
setTimeout(operation(function() {
if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
var no = lineNo(oldLine);
replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
}
}, 10));
}
}
sel.from = from; sel.to = to;
selectionChanged = true;
}
@ -1164,6 +1262,7 @@ var CodeMirror = (function() {
if (unit == "page") dist = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
else if (unit == "line") dist = textHeight();
var target = coordsChar(pos.x, pos.y + dist * dir + 2);
if (unit == "page") scroller.scrollTop += localCoords(target, true).y - pos.y;
setCursor(target.line, target.ch, true);
goalColumn = pos.x;
}
@ -1176,7 +1275,7 @@ var CodeMirror = (function() {
setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
}
function selectLine(line) {
setSelectionUser({line: line, ch: 0}, {line: line, ch: getLine(line).text.length});
setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0}));
}
function indentSelected(mode) {
if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
@ -1249,13 +1348,11 @@ var CodeMirror = (function() {
}
changes.push({from: 0, to: doc.size});
}
function computeTabText() {
for (var str = '<span class="cm-tab">', i = 0; i < options.tabSize; ++i) str += " ";
return str + "</span>";
}
function tabsChanged() {
tabText = computeTabText();
updateDisplay(true);
function makeTab(col) {
var w = options.tabSize - col % options.tabSize, cached = tabCache[w];
if (cached) return cached;
for (var str = '<span class="cm-tab">', i = 0; i < w; ++i) str += " ";
return (tabCache[w] = {html: str + "</span>", width: w});
}
function themeChanged() {
scroller.className = scroller.className.replace(/\s*cm-s-\w+/g, "") +
@ -1271,7 +1368,7 @@ var CodeMirror = (function() {
var lineN = lineNo(line);
min = Math.min(min, lineN); max = Math.max(max, lineN);
for (var j = 0; j < mk.length; ++j)
if (mk[j].set == this.set) mk.splice(j--, 1);
if (mk[j].marker == this) mk.splice(j--, 1);
}
if (min != Infinity)
changes.push({from: min, to: max + 1});
@ -1282,7 +1379,7 @@ var CodeMirror = (function() {
var line = this.set[i], mk = line.marked;
for (var j = 0; j < mk.length; ++j) {
var mark = mk[j];
if (mark.set == this.set) {
if (mark.marker == this) {
if (mark.from != null || mark.to != null) {
var found = lineNo(line);
if (found != null) {
@ -1299,8 +1396,9 @@ var CodeMirror = (function() {
function markText(from, to, className) {
from = clipPos(from); to = clipPos(to);
var tm = new TextMarker();
if (!posLess(from, to)) return tm;
function add(line, from, to, className) {
getLine(line).addMark(new MarkedText(from, to, className, tm.set));
getLine(line).addMark(new MarkedText(from, to, className, tm));
}
if (from.line == to.line) add(from.line, from.ch, to.ch, className);
else {
@ -1320,6 +1418,19 @@ var CodeMirror = (function() {
return bm;
}
function findMarksAt(pos) {
pos = clipPos(pos);
var markers = [], marked = getLine(pos.line).marked;
if (!marked) return markers;
for (var i = 0, e = marked.length; i < e; ++i) {
var m = marked[i];
if ((m.from == null || m.from <= pos.ch) &&
(m.to == null || m.to >= pos.ch))
markers.push(m.marker || m);
}
return markers;
}
function addGutterMarker(line, text, className) {
if (typeof line == "number") line = getLine(clipLine(line));
line.gutterMarker = {text: text, style: className};
@ -1341,10 +1452,11 @@ var CodeMirror = (function() {
else return null;
return line;
}
function setLineClass(handle, className) {
function setLineClass(handle, className, bgClassName) {
return changeLine(handle, function(line) {
if (line.className != className) {
if (line.className != className || line.bgClassName != bgClassName) {
line.className = className;
line.bgClassName = bgClassName;
return true;
}
});
@ -1358,6 +1470,8 @@ var CodeMirror = (function() {
if (hidden && (fline == no || tline == no)) {
var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from;
var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to;
// Can't hide the last visible line, we'd have no place to put the cursor
if (!to) return;
setSelection(from, to);
}
return (gutterDirty = true);
@ -1378,7 +1492,7 @@ var CodeMirror = (function() {
}
var marker = line.gutterMarker;
return {line: n, handle: line, text: line.text, markerText: marker && marker.text,
markerClass: marker && marker.style, lineClass: line.className};
markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName};
}
function stringWidth(str) {
@ -1392,7 +1506,7 @@ var CodeMirror = (function() {
if (x <= 0) return 0;
var lineObj = getLine(line), text = lineObj.text;
function getX(len) {
measure.innerHTML = "<pre><span>" + lineObj.getHTML(tabText, len) + "</span></pre>";
measure.innerHTML = "<pre><span>" + lineObj.getHTML(makeTab, len) + "</span></pre>";
return measure.firstChild.firstChild.offsetWidth;
}
var from = 0, fromX = 0, to = text.length, toX;
@ -1422,10 +1536,10 @@ var CodeMirror = (function() {
var extra = "";
// Include extra text at the end to make sure the measured line is wrapped in the right way.
if (options.lineWrapping) {
var end = line.text.indexOf(" ", ch + 2);
var end = line.text.indexOf(" ", ch + 6);
extra = htmlEscape(line.text.slice(ch + 1, end < 0 ? line.text.length : end + (ie ? 5 : 0)));
}
measure.innerHTML = "<pre>" + line.getHTML(tabText, ch) +
measure.innerHTML = "<pre>" + line.getHTML(makeTab, ch) +
'<span id="CodeMirror-temp-' + tempId + '">' + htmlEscape(line.text.charAt(ch) || " ") + "</span>" +
extra + "</pre>";
var elt = document.getElementById("CodeMirror-temp-" + tempId);
@ -1528,7 +1642,7 @@ var CodeMirror = (function() {
return coordsChar(x - offL.left, y - offL.top);
}
function onContextMenu(e) {
var pos = posFromMouse(e);
var pos = posFromMouse(e), scrollPos = scroller.scrollTop;
if (!pos || window.opera) return; // Opera is difficult.
if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
operation(setCursor)(pos.line, pos.ch);
@ -1541,12 +1655,13 @@ var CodeMirror = (function() {
leaveInputAlone = true;
var val = input.value = getSelection();
focusInput();
input.select();
selectInput(input);
function rehide() {
var newVal = splitLines(input.value).join("\n");
if (newVal != val) operation(replaceSelection)(newVal, "end");
inputDiv.style.position = "relative";
input.style.cssText = oldCSS;
if (ie_lt9) scroller.scrollTop = scrollPos;
leaveInputAlone = false;
resetInput(true);
slowPoll();
@ -1558,8 +1673,7 @@ var CodeMirror = (function() {
mouseup();
setTimeout(rehide, 20);
}, true);
}
else {
} else {
setTimeout(rehide, 50);
}
}
@ -1761,6 +1875,7 @@ var CodeMirror = (function() {
keyMap: "default",
extraKeys: null,
electricChars: true,
autoClearEmptyLines: false,
onKeyEvent: null,
lineWrapping: false,
lineNumbers: false,
@ -1780,7 +1895,7 @@ var CodeMirror = (function() {
pollInterval: 100,
undoDepth: 40,
tabindex: null,
document: window.document
autofocus: null
};
var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
@ -1788,7 +1903,7 @@ var CodeMirror = (function() {
var win = /Win/.test(navigator.platform);
// Known modes, by name and by MIME
var modes = {}, mimeModes = {};
var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
CodeMirror.defineMode = function(name, mode) {
if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
modes[name] = mode;
@ -1796,19 +1911,22 @@ var CodeMirror = (function() {
CodeMirror.defineMIME = function(mime, spec) {
mimeModes[mime] = spec;
};
CodeMirror.getMode = function(options, spec) {
CodeMirror.resolveMode = function(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
spec = mimeModes[spec];
if (typeof spec == "string")
var mname = spec, config = {};
else if (spec != null)
var mname = spec.name, config = spec;
var mfactory = modes[mname];
else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
return CodeMirror.resolveMode("application/xml");
if (typeof spec == "string") return {name: spec};
else return spec || {name: "null"};
};
CodeMirror.getMode = function(options, spec) {
var spec = CodeMirror.resolveMode(spec);
var mfactory = modes[spec.name];
if (!mfactory) {
if (window.console) console.warn("No mode " + mname + " found, falling back to plain text.");
if (window.console) console.warn("No mode " + spec.name + " found, falling back to plain text.");
return CodeMirror.getMode(options, "text/plain");
}
return mfactory(options, config || {});
return mfactory(options, spec);
};
CodeMirror.listModes = function() {
var list = [];
@ -1882,7 +2000,7 @@ var CodeMirror = (function() {
keyMap.basic = {
"Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
"End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
"Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "indentMore", "Shift-Tab": "indentLess",
"Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "insertTab", "Shift-Tab": "indentAuto",
"Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
};
// Note that the save and find-related commands aren't defined by
@ -1893,6 +2011,7 @@ var CodeMirror = (function() {
"Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
"Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find",
"Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
"Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
fallthrough: "basic"
};
keyMap.macDefault = {
@ -1901,6 +2020,7 @@ var CodeMirror = (function() {
"Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft",
"Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find",
"Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
"Cmd-[": "indentLess", "Cmd-]": "indentMore",
fallthrough: ["basic", "emacsy"]
};
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
@ -1911,20 +2031,27 @@ var CodeMirror = (function() {
"Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
};
function lookupKey(name, extraMap, map) {
function lookup(name, map, ft) {
function getKeyMap(val) {
if (typeof val == "string") return keyMap[val];
else return val;
}
function lookupKey(name, extraMap, map, handle) {
function lookup(map) {
map = getKeyMap(map);
var found = map[name];
if (found != null) return found;
if (ft == null) ft = map.fallthrough;
if (ft == null) return map.catchall;
if (typeof ft == "string") return lookup(name, keyMap[ft]);
for (var i = 0, e = ft.length; i < e; ++i) {
found = lookup(name, keyMap[ft[i]]);
if (found != null) return found;
if (found != null && handle(found)) return true;
if (map.catchall) return handle(map.catchall);
var fallthrough = map.fallthrough;
if (fallthrough == null) return false;
if (Object.prototype.toString.call(fallthrough) != "[object Array]")
return lookup(fallthrough);
for (var i = 0, e = fallthrough.length; i < e; ++i) {
if (lookup(fallthrough[i])) return true;
}
return null;
return false;
}
return extraMap ? lookup(name, extraMap, map) : lookup(name, keyMap[map]);
if (extraMap && lookup(extraMap)) return true;
return lookup(map);
}
function isModifierKey(event) {
var name = keyNames[e_prop(event, "keyCode")];
@ -1936,6 +2063,8 @@ var CodeMirror = (function() {
options.value = textarea.value;
if (!options.tabindex && textarea.tabindex)
options.tabindex = textarea.tabindex;
if (options.autofocus == null && textarea.getAttribute("autofocus") != null)
options.autofocus = true;
function save() {textarea.value = instance.getValue();}
if (textarea.form) {
@ -2047,34 +2176,34 @@ var CodeMirror = (function() {
};
CodeMirror.StringStream = StringStream;
function MarkedText(from, to, className, set) {
this.from = from; this.to = to; this.style = className; this.set = set;
function MarkedText(from, to, className, marker) {
this.from = from; this.to = to; this.style = className; this.marker = marker;
}
MarkedText.prototype = {
attach: function(line) { this.set.push(line); },
attach: function(line) { this.marker.set.push(line); },
detach: function(line) {
var ix = indexOf(this.set, line);
if (ix > -1) this.set.splice(ix, 1);
var ix = indexOf(this.marker.set, line);
if (ix > -1) this.marker.set.splice(ix, 1);
},
split: function(pos, lenBefore) {
if (this.to <= pos && this.to != null) return null;
var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore;
var to = this.to == null ? null : this.to - pos + lenBefore;
return new MarkedText(from, to, this.style, this.set);
return new MarkedText(from, to, this.style, this.marker);
},
dup: function() { return new MarkedText(null, null, this.style, this.set); },
dup: function() { return new MarkedText(null, null, this.style, this.marker); },
clipTo: function(fromOpen, from, toOpen, to, diff) {
if (this.from != null && this.from >= from)
this.from = Math.max(to, this.from) + diff;
if (this.to != null && this.to > from)
this.to = to < this.to ? this.to + diff : from;
if (fromOpen && to > this.from && (to < this.to || this.to == null))
this.from = null;
else if (this.from != null && this.from >= from)
this.from = Math.max(to, this.from) + diff;
if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null))
this.to = null;
else if (this.to != null && this.to > from)
this.to = to < this.to ? this.to + diff : from;
},
isDead: function() { return this.from != null && this.to != null && this.from >= this.to; },
sameSet: function(x) { return this.set == x.set; }
sameSet: function(x) { return this.marker == x.marker; }
};
function Bookmark(pos) {
@ -2117,7 +2246,7 @@ var CodeMirror = (function() {
this.styles = styles || [text, null];
this.text = text;
this.height = 1;
this.marked = this.gutterMarker = this.className = this.handlers = null;
this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null;
this.stateAfter = this.parent = this.hidden = null;
}
Line.inheritMarks = function(text, orig) {
@ -2163,6 +2292,7 @@ var CodeMirror = (function() {
if (newmark) {
if (!taken.marked) taken.marked = [];
taken.marked.push(newmark); newmark.attach(taken);
if (newmark == mark) mk.splice(i--, 1);
}
}
}
@ -2272,15 +2402,35 @@ var CodeMirror = (function() {
indentation: function(tabSize) {return countColumn(this.text, null, tabSize);},
// Produces an HTML fragment for the line, taking selection,
// marking, and highlighting into account.
getHTML: function(tabText, endAt) {
var html = [], first = true;
getHTML: function(makeTab, endAt) {
var html = [], first = true, col = 0;
function span(text, style) {
if (!text) return;
// Work around a bug where, in some compat modes, IE ignores leading spaces
if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1);
first = false;
if (style) html.push('<span class="', style, '">', htmlEscape(text).replace(/\t/g, tabText), "</span>");
else html.push(htmlEscape(text).replace(/\t/g, tabText));
if (text.indexOf("\t") == -1) {
col += text.length;
var escaped = htmlEscape(text);
} else {
var escaped = "";
for (var pos = 0;;) {
var idx = text.indexOf("\t", pos);
if (idx == -1) {
escaped += htmlEscape(text.slice(pos));
col += text.length - pos;
break;
} else {
col += idx - pos;
var tab = makeTab(col);
escaped += htmlEscape(text.slice(pos, idx)) + tab.html;
col += tab.width;
pos = idx + 1;
}
}
}
if (style) html.push('<span class="', style, '">', escaped, "</span>");
else html.push(escaped);
}
var st = this.styles, allText = this.text, marked = this.marked;
var len = allText.length;
@ -2559,17 +2709,17 @@ var CodeMirror = (function() {
var dtime = time - this.time;
if (dtime > 400 || !last) {
this.done.push([{start: start, added: added, old: old}]);
} else if (last.start > start + added || last.start + last.added < start - last.added + last.old.length) {
} else if (last.start > start + old.length || last.start + last.added < start - last.added + last.old.length) {
cur.push({start: start, added: added, old: old});
} else {
var oldoff = 0;
if (start < last.start) {
for (var i = last.start - start - 1; i >= 0; --i)
last.old.unshift(old[i]);
last.added += last.start - start;
oldoff = Math.min(0, added - old.length);
last.added += last.start - start + oldoff;
last.start = start;
}
else if (last.start < start) {
} else if (last.start < start) {
oldoff = start - last.start;
added += oldoff;
}
@ -2634,18 +2784,23 @@ var CodeMirror = (function() {
function Delayed() {this.id = null;}
Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
// Detect drag-and-drop
var dragAndDrop = function() {
// IE8 has ondragstart and ondrop properties, but doesn't seem to
// actually support ondragstart the way it's supposed to work.
if (/MSIE [1-8]\b/.test(navigator.userAgent)) return false;
var div = document.createElement('div');
return "draggable" in div;
}();
var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
var ie = /MSIE \d/.test(navigator.userAgent);
var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
var webkit = /WebKit\//.test(navigator.userAgent);
var chrome = /Chrome\//.test(navigator.userAgent);
var khtml = /KHTML\//.test(navigator.userAgent);
// Detect drag-and-drop
var dragAndDrop = function() {
// There is *some* kind of drag-and-drop support in IE6-8, but I
// couldn't get it to work yet.
if (ie_lt9) return false;
var div = document.createElement('div');
return "draggable" in div || "dragDrop" in div;
}();
var lineSep = "\n";
// Feature-detect whether newlines in textareas are converted to \r\n
@ -2799,7 +2954,7 @@ var CodeMirror = (function() {
var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 186: ";", 187: "=", 188: ",",
46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 127: "Delete", 186: ";", 187: "=", 188: ",",
189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp",
63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right",
63233: "Down", 63302: "Insert", 63272: "Delete"};

View File

@ -319,8 +319,8 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
kwAllowed: true,
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: null,
context: null,
localVars: parserConfig.localVars,
context: parserConfig.localVars && {vars: parserConfig.localVars},
indented: 0
};
},
@ -334,7 +334,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.reAllowed = type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/);
state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/));
state.kwAllowed = type != '.';
return parseJS(state, style, type, content, stream);
},

View File

@ -193,8 +193,8 @@ if (!JSON) {
};
}
var cx = new RegExp('/[\u0000\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', 'g'),
escapable = new RegExp('/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', 'g'),
var cx = new RegExp('[\u0000\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', 'g'),
escapable = new RegExp('[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', 'g'),
gap,
indent,
meta = { // table of character substitutions

12
node_modules/esprima/assets/yui/treeview-min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

BIN
node_modules/esprima/assets/yui/treeview-sprite.gif generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

7
node_modules/esprima/assets/yui/treeview.css generated vendored Normal file
View File

@ -0,0 +1,7 @@
/*
Copyright (c) 2011, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 2.9.0
*/
table.ygtvtable{margin-bottom:0;border:0;border-collapse:collapse}td.ygtvcell{border:0;padding:0}a.ygtvspacer{text-decoration:none;outline-style:none;display:block}.ygtvtn{width:18px;height:22px;background:url(treeview-sprite.gif) 0 -5600px no-repeat;cursor:pointer}.ygtvtm{width:18px;height:22px;cursor:pointer;background:url(treeview-sprite.gif) 0 -4000px no-repeat}.ygtvtmh,.ygtvtmhh{width:18px;height:22px;cursor:pointer;background:url(treeview-sprite.gif) 0 -4800px no-repeat}.ygtvtp{width:18px;height:22px;cursor:pointer;background:url(treeview-sprite.gif) 0 -6400px no-repeat}.ygtvtph,.ygtvtphh{width:18px;height:22px;cursor:pointer;background:url(treeview-sprite.gif) 0 -7200px no-repeat}.ygtvln{width:18px;height:22px;background:url(treeview-sprite.gif) 0 -1600px no-repeat;cursor:pointer}.ygtvlm{width:18px;height:22px;cursor:pointer;background:url(treeview-sprite.gif) 0 0 no-repeat}.ygtvlmh,.ygtvlmhh{width:18px;height:22px;cursor:pointer;background:url(treeview-sprite.gif) 0 -800px no-repeat}.ygtvlp{width:18px;height:22px;cursor:pointer;background:url(treeview-sprite.gif) 0 -2400px no-repeat}.ygtvlph,.ygtvlphh{width:18px;height:22px;cursor:pointer;background:url(treeview-sprite.gif) 0 -3200px no-repeat;cursor:pointer}.ygtvloading{width:18px;height:22px;background:url(treeview-loading.gif) 0 0 no-repeat}.ygtvdepthcell{width:18px;height:22px;background:url(treeview-sprite.gif) 0 -8000px no-repeat}.ygtvblankdepthcell{width:18px;height:22px}* html .ygtvchildren{height:2%}.ygtvlabel,.ygtvlabel:link,.ygtvlabel:visited,.ygtvlabel:hover{margin-left:2px;text-decoration:none;background-color:white;cursor:pointer}.ygtvcontent{cursor:default}.ygtvspacer{height:22px;width:18px}.ygtvfocus{background-color:#c0e0e0;border:0}.ygtvfocus .ygtvlabel,.ygtvfocus .ygtvlabel:link,.ygtvfocus .ygtvlabel:visited,.ygtvfocus .ygtvlabel:hover{background-color:#c0e0e0}.ygtvfocus a{outline-style:none}.ygtvok{width:18px;height:22px;background:url(treeview-sprite.gif) 0 -8800px no-repeat}.ygtvok:hover{background:url(treeview-sprite.gif) 0 -8844px no-repeat}.ygtvcancel{width:18px;height:22px;background:url(treeview-sprite.gif) 0 -8822px no-repeat}.ygtvcancel:hover{background:url(treeview-sprite.gif) 0 -8866px no-repeat}.ygtv-label-editor{background-color:#f2f2f2;border:1px solid silver;position:absolute;display:none;overflow:hidden;margin:auto;z-index:9000}.ygtv-edit-TextNode{width:190px}.ygtv-edit-TextNode .ygtvcancel,.ygtv-edit-TextNode .ygtvok{border:0}.ygtv-edit-TextNode .ygtv-button-container{float:right}.ygtv-edit-TextNode .ygtv-input input{width:140px}.ygtv-edit-DateNode .ygtvcancel{border:0}.ygtv-edit-DateNode .ygtvok{display:none}.ygtv-edit-DateNode .ygtv-button-container{text-align:right;margin:auto}.ygtv-highlight .ygtv-highlight1,.ygtv-highlight .ygtv-highlight1 .ygtvlabel{background-color:blue;color:white}.ygtv-highlight .ygtv-highlight2,.ygtv-highlight .ygtv-highlight2 .ygtvlabel{background-color:silver}.ygtv-highlight .ygtv-highlight0 .ygtvfocus .ygtvlabel,.ygtv-highlight .ygtv-highlight1 .ygtvfocus .ygtvlabel,.ygtv-highlight .ygtv-highlight2 .ygtvfocus .ygtvlabel{background-color:#c0e0e0}.ygtv-highlight .ygtvcontent{padding-right:1em}.ygtv-checkbox .ygtv-highlight0 .ygtvcontent{padding-left:1em;background:url(check0.gif) no-repeat}.ygtv-checkbox .ygtv-highlight0 .ygtvfocus.ygtvcontent,.ygtv-checkbox .ygtv-highlight1 .ygtvfocus.ygtvcontent,.ygtv-checkbox .ygtv-highlight2 .ygtvfocus.ygtvcontent{background-color:#c0e0e0}.ygtv-checkbox .ygtv-highlight1 .ygtvcontent{padding-left:1em;background:url(check1.gif) no-repeat}.ygtv-checkbox .ygtv-highlight2 .ygtvcontent{padding-left:1em;background:url(check2.gif) no-repeat}

14
node_modules/esprima/assets/yui/yahoo-dom-event.js generated vendored Normal file

File diff suppressed because one or more lines are too long

92
node_modules/esprima/changes generated vendored Normal file
View File

@ -0,0 +1,92 @@
Update escodegen for the rewrite demo.
Update CodeMirror to version 2.23.
Collect the last line comment.
Dynamically loading Narcissus in the speed comparison page.
Show an exemplary coverage analysis result.
Generate coverage analysis report.
Tree interface for the parse demo.
Use increment operator in various scanning functions.
Use increment operator in comment handling functions.
Unbreak the test suite on older web browsers.
Reenable testing with Node.js 0.4.
Compensate if invalid regular expression flag is not handled correctly.
Mention github.com/Yoric/Marv-the-Tinker.
Preserve line terminators in block comments
Tolerant mode: ignore with restriction
Do not use Object.freeze for various hash tables.
Simplify nextChar() function with increment operator.
Tolerant mode: ignore return not within a function
Import Esmorph code for the Function Trace demo.
Remove source modification feature.
Reorganize binary node tracking routines.
Vary parsing options while testing for invalid syntax.
Fix wrong location info when comments are present.
Add a test case for do while ended with a semicolon.
Add a test case for continue statement with a semicolon.
Shuffle the code in wrapTrackingFunction() function.
Import escodegen for the Source Rewrite demo.
Split code generator from esprima core
Add test cases for reserved words as function argument name.
Add a test case for using future reserved word as function name.
Shuffle the code in parseSourceElement() function.
Add a test case for computed member in left hand-side expression.
Make note of unreachable case when parsing object property key.
Update CodeMirror to version 2.22.
Update platform.js to v1.0.0-pre.
Temporarily disable Travis CI test on Node.js 0.4.
Add a test case to trigger an error due to expecting a keyword.
No need to shorten the token value for unexpected token error.
Add a test case for (invalid) Unicode escape in regular expression flag.
Add a test case for octal directive restriction before strict directive in Program
Strict mode: duplicate identifier in function parameter list
Add a test case for an error of non-identifier after non-computed property.
Syntax errors for duplicate object properties.
Fixed property name error message identifiers.
Add test cases to capture some escaping in the string literals.
Add test cases for invalid octal literals.
Add a test case for semicolon after a comment.
Add a test case to provoke an error in the object property setter.
Add test cases for break and continue followed by a line break.
Add a test case for empty source elements.
Use assert for better semantics of contract.
Reject illegal numeric literal like '10E+'
ArrayInitialiser / ObjectInitialiser don't handle end-of-input correctly
Add tests to catch various corner cases when handling Unicode literals.
Static mapping of token value and its name.
Incomplete statement should trigger an error.
Remove unused function unpatching after the refactoring.
Support space separator as white space
Add comment about following V8 error messages.
Fix syntax error message strings.
Handle LHS in for-in and assignment correctly
SyntaxError for 'return' outside function body
Mention related projects based on Esprima.
IE6 fix for parser demo error reporting.
IE6 fixes for labelSet.
Fix coding style violations in the new isKeyword() function.
Syntax errors for invalid continue/break and label references
Faster isKeyword() implementation.
Add generator identity test
Freeze constant values
Remove some invalid Precedence
generate() fails on consecutive unary expressions.
Optimize moving the index forward instead of calling nextChar().
Add API test cases for Mozilla Reflect compatibility.
Add support for indentation option in the rewriter demo.
New demo to showcase source code rewrite.
Simplify nextChar() function.
Unterminated block comment should trigger an error.
Make the regular expressions for `IdentifierStart` and `IdentifierPart` more compact
Strict Mode: restrict with statement
Duplicated property check should be robust against special name.
Fix code generator with an empty program.
Fix generator indentation bug in double nested If statements.
Allow some future reserved word in non-strict code.
Unnecessary forward slash in json2.js Opera fix.
Strict mode: do not allow octal literals.
Fixed null literal value property.
Clean-up unused variables.
Strict mode: trigger an error when using eval and arguments.
Mark numeric literal specified as an octal number.
Fix Unicode bug with Letter number (Nl) and `\u200C` or `\u200D`.
Include the forgotten Python script to generated Unicode regex.

696
node_modules/esprima/cm generated vendored Normal file
View File

@ -0,0 +1,696 @@
commit f2dd82b0d3defdedb01c5222e802d56ba47bd93f
Author: Ariya Hidayat <ariya.hidayat@gmail.com>
Date: Tue Mar 27 17:56:26 2012 -0700
CodeMirror version 2.23.
diff --git a/assets/codemirror/codemirror.css b/assets/codemirror/codemirror.css
index 5eadb24..2d79f4a 100644
--- a/assets/codemirror/codemirror.css
+++ b/assets/codemirror/codemirror.css
@@ -9,6 +9,7 @@
/* This is needed to prevent an IE[67] bug where the scrolled content
is visible outside of the scrolling box. */
position: relative;
+ outline: none;
}
.CodeMirror-gutter {
@@ -27,6 +28,7 @@
}
.CodeMirror-lines {
padding: .4em;
+ white-space: pre;
}
.CodeMirror pre {
diff --git a/assets/codemirror/codemirror.js b/assets/codemirror/codemirror.js
index 9c6e65e..5434a8d 100644
--- a/assets/codemirror/codemirror.js
+++ b/assets/codemirror/codemirror.js
@@ -1,4 +1,4 @@
-// CodeMirror version 2.22
+// CodeMirror version 2.23
//
// All functions that need access to the editor's state live inside
// the CodeMirror function. Below that, at the bottom of the file,
@@ -15,9 +15,8 @@ var CodeMirror = (function() {
if (defaults.hasOwnProperty(opt))
options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
- var targetDocument = options["document"];
// The element in which the editor lives.
- var wrapper = targetDocument.createElement("div");
+ var wrapper = document.createElement("div");
wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "");
// This mess creates the base DOM structure for the editor.
wrapper.innerHTML =
@@ -48,7 +47,10 @@ var CodeMirror = (function() {
if (!webkit) lineSpace.draggable = true;
lineSpace.style.outline = "none";
if (options.tabindex != null) input.tabIndex = options.tabindex;
+ if (options.autofocus) focusInput();
if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
+ // Needed to handle Tab key in KHTML
+ if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute";
// Check for problem with IE innerHTML not working when we have a
// P (or similar) parent node.
@@ -81,12 +83,13 @@ var CodeMirror = (function() {
gutterDirty, callbacks;
// Current visible range (may be bigger than the view window).
var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
- // bracketHighlighted is used to remember that a backet has been
+ // bracketHighlighted is used to remember that a bracket has been
// marked.
var bracketHighlighted;
// Tracks the maximum line length so that the horizontal scrollbar
// can be kept static when scrolling.
var maxLine = "", maxWidth;
+ var tabCache = {};
// Initialize the content.
operation(function(){setValue(options.value || ""); updateInput = false;})();
@@ -124,10 +127,16 @@ var CodeMirror = (function() {
if (!options.readOnly) replaceSelection("");
}));
+ // Needed to handle Tab key in KHTML
+ if (khtml) connect(code, "mouseup", function() {
+ if (document.activeElement == input) input.blur();
+ focusInput();
+ });
+
// IE throws unspecified error in certain cases, when
// trying to access activeElement before onload
- var hasFocus; try { hasFocus = (targetDocument.activeElement == input); } catch(e) { }
- if (hasFocus) setTimeout(onFocus, 20);
+ var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { }
+ if (hasFocus || options.autofocus) setTimeout(onFocus, 20);
else onBlur();
function isLine(l) {return l >= 0 && l < doc.size;}
@@ -178,17 +187,23 @@ var CodeMirror = (function() {
line = clipLine(line == null ? doc.size - 1: line);
return getStateBefore(line + 1);
},
- cursorCoords: function(start){
+ cursorCoords: function(start, mode) {
if (start == null) start = sel.inverted;
- return pageCoords(start ? sel.from : sel.to);
+ return this.charCoords(start ? sel.from : sel.to, mode);
+ },
+ charCoords: function(pos, mode) {
+ pos = clipPos(pos);
+ if (mode == "local") return localCoords(pos, false);
+ if (mode == "div") return localCoords(pos, true);
+ return pageCoords(pos);
},
- charCoords: function(pos){return pageCoords(clipPos(pos));},
coordsChar: function(coords) {
var off = eltOffset(lineSpace);
return coordsChar(coords.x - off.left, coords.y - off.top);
},
markText: operation(markText),
setBookmark: setBookmark,
+ findMarksAt: findMarksAt,
setMarker: operation(addGutterMarker),
clearMarker: operation(removeGutterMarker),
setLineClass: operation(setLineClass),
@@ -256,6 +271,7 @@ var CodeMirror = (function() {
replaceRange: operation(replaceRange),
getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
+ triggerOnKeyDown: operation(onKeyDown),
execCommand: function(cmd) {return commands[cmd](instance);},
// Stuff used by commands, probably not much use to outside code.
moveH: operation(moveH),
@@ -373,7 +389,7 @@ var CodeMirror = (function() {
!posLess(start, sel.from) && !posLess(sel.to, start)) {
// Let the drag handler handle this.
if (webkit) lineSpace.draggable = true;
- var up = connect(targetDocument, "mouseup", operation(function(e2) {
+ var up = connect(document, "mouseup", operation(function(e2) {
if (webkit) lineSpace.draggable = false;
draggingText = false;
up();
@@ -384,6 +400,8 @@ var CodeMirror = (function() {
}
}), true);
draggingText = true;
+ // IE's approach to draggable
+ if (lineSpace.dragDrop) lineSpace.dragDrop();
return;
}
e_preventDefault(e);
@@ -402,12 +420,7 @@ var CodeMirror = (function() {
}
}
- var move = connect(targetDocument, "mousemove", operation(function(e) {
- clearTimeout(going);
- e_preventDefault(e);
- extend(e);
- }), true);
- var up = connect(targetDocument, "mouseup", operation(function(e) {
+ function done(e) {
clearTimeout(going);
var cur = posFromMouse(e);
if (cur) setSelectionUser(start, cur);
@@ -415,7 +428,14 @@ var CodeMirror = (function() {
focusInput();
updateInput = true;
move(); up();
+ }
+ var move = connect(document, "mousemove", operation(function(e) {
+ clearTimeout(going);
+ e_preventDefault(e);
+ if (!ie && !e_button(e)) done(e);
+ else extend(e);
}), true);
+ var up = connect(document, "mouseup", operation(done), true);
}
function onDoubleClick(e) {
for (var n = e_target(e); n != wrapper; n = n.parentNode)
@@ -464,11 +484,14 @@ var CodeMirror = (function() {
}
function onDragStart(e) {
var txt = getSelection();
- // Disabled until further notice. Doesn't work on most browsers,
- // and crashes Safari (issue #332).
- //htmlEscape(txt);
- //e.dataTransfer.setDragImage(escapeElement, 0, 0);
e.dataTransfer.setData("Text", txt);
+
+ // Use dummy image instead of default browsers image.
+ if (gecko || chrome) {
+ var img = document.createElement('img');
+ img.scr = 'data:image/gif;base64,R0lGODdhAgACAIAAAAAAAP///ywAAAAAAgACAAACAoRRADs='; //1x1 image
+ e.dataTransfer.setDragImage(img, 0, 0);
+ }
}
function doHandleBinding(bound, dropShift) {
@@ -506,13 +529,19 @@ var CodeMirror = (function() {
if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name;
if (e_prop(e, "metaKey")) name = "Cmd-" + name;
- if (e_prop(e, "shiftKey"))
+ if (e_prop(e, "shiftKey")) {
handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap,
- function(b) {return doHandleBinding(b, true);});
- if (!handled)
+ function(b) {return doHandleBinding(b, true);})
+ || lookupKey(name, options.extraKeys, options.keyMap, function(b) {
+ if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b);
+ });
+ } else {
handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding);
-
- if (handled) e_preventDefault(e);
+ }
+ if (handled) {
+ e_preventDefault(e);
+ if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
+ }
return handled;
}
function handleCharBinding(e, ch) {
@@ -545,7 +574,7 @@ var CodeMirror = (function() {
if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
if (window.opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
- if (window.opera && !e.which && handleKeyBinding(e)) return;
+ if (((window.opera && !e.which) || khtml) && handleKeyBinding(e)) return;
var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) {
if (mode.electricChars.indexOf(ch) > -1)
@@ -837,11 +866,11 @@ var CodeMirror = (function() {
return scrollIntoView(x, cursor.y, x, cursor.yBot);
}
function scrollIntoView(x1, y1, x2, y2) {
- var pl = paddingLeft(), pt = paddingTop(), lh = textHeight();
+ var pl = paddingLeft(), pt = paddingTop();
y1 += pt; y2 += pt; x1 += pl; x2 += pl;
var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
- if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1 - 2*lh); scrolled = true;}
- else if (y2 > screentop + screen) {scroller.scrollTop = y2 + lh - screen; scrolled = true;}
+ if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1); scrolled = true;}
+ else if (y2 > screentop + screen) {scroller.scrollTop = y2 - screen; scrolled = true;}
var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
@@ -921,7 +950,7 @@ var CodeMirror = (function() {
throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) +
" nodes=" + lineDiv.childNodes.length);
- if (options.lineWrapping) {
+ function checkHeights() {
maxWidth = scroller.clientWidth;
var curNode = lineDiv.firstChild, heightChanged = false;
doc.iter(showingFrom, showingTo, function(line) {
@@ -936,6 +965,11 @@ var CodeMirror = (function() {
});
if (heightChanged)
code.style.height = (doc.height * th + 2 * paddingTop()) + "px";
+ return heightChanged;
+ }
+
+ if (options.lineWrapping) {
+ checkHeights();
} else {
if (maxWidth == null) maxWidth = stringWidth(maxLine);
if (maxWidth > scroller.clientWidth) {
@@ -947,8 +981,12 @@ var CodeMirror = (function() {
lineSpace.style.width = code.style.width = "";
}
}
+
gutter.style.display = gutterDisplay;
- if (different || gutterDirty) updateGutter();
+ if (different || gutterDirty) {
+ // If the gutter grew in size, re-check heights. If those changed, re-draw gutter.
+ updateGutter() && options.lineWrapping && checkHeights() && updateGutter();
+ }
updateSelection();
if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
return true;
@@ -996,16 +1034,17 @@ var CodeMirror = (function() {
}
// This pass fills in the lines that actually changed.
var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
- var scratch = targetDocument.createElement("div"), newElt;
+ var scratch = document.createElement("div");
doc.iter(from, to, function(line) {
if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
if (!nextIntact || nextIntact.from > j) {
if (line.hidden) var html = scratch.innerHTML = "<pre></pre>";
else {
- var html = '<pre>' + line.getHTML(makeTab) + '</pre>';
+ var html = '<pre' + (line.className ? ' class="' + line.className + '"' : '') + '>'
+ + line.getHTML(makeTab) + '</pre>';
// Kludge to make sure the styled element lies behind the selection (by z-index)
- if (line.className)
- html = '<div style="position: relative"><pre class="' + line.className +
+ if (line.bgClassName)
+ html = '<div style="position: relative"><pre class="' + line.bgClassName +
'" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2">&#160;</pre>' + html + "</div>";
}
scratch.innerHTML = html;
@@ -1021,7 +1060,7 @@ var CodeMirror = (function() {
if (!options.gutter && !options.lineNumbers) return;
var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
- var html = [], i = showingFrom;
+ var html = [], i = showingFrom, normalNode;
doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
if (line.hidden) {
html.push("<pre></pre>");
@@ -1035,17 +1074,24 @@ var CodeMirror = (function() {
html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text);
for (var j = 1; j < line.height; ++j) html.push("<br/>&#160;");
html.push("</pre>");
+ if (!marker) normalNode = i;
}
++i;
});
gutter.style.display = "none";
gutterText.innerHTML = html.join("");
- var minwidth = String(doc.size).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = "";
- while (val.length + pad.length < minwidth) pad += "\u00a0";
- if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild);
+ // Make sure scrolling doesn't cause number gutter size to pop
+ if (normalNode != null) {
+ var node = gutterText.childNodes[normalNode - showingFrom];
+ var minwidth = String(doc.size).length, val = eltText(node), pad = "";
+ while (val.length + pad.length < minwidth) pad += "\u00a0";
+ if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild);
+ }
gutter.style.display = "";
+ var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2;
lineSpace.style.marginLeft = gutter.offsetWidth + "px";
gutterDirty = false;
+ return resized;
}
function updateSelection() {
var collapsed = posEq(sel.from, sel.to);
@@ -1066,16 +1112,18 @@ var CodeMirror = (function() {
html += '<div class="CodeMirror-selected" style="position: absolute; left: ' + left +
'px; top: ' + top + 'px; right: ' + right + 'px; height: ' + height + 'px"></div>';
}
+ var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth;
+ var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight;
if (sel.from.ch && fromPos.y >= 0) {
- var right = sameLine ? lineSpace.clientWidth - toPos.x : 0;
+ var right = sameLine ? clientWidth - toPos.x : 0;
add(fromPos.x, fromPos.y, right, th);
}
var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0));
- var middleHeight = Math.min(toPos.y, lineSpace.clientHeight) - middleStart;
+ var middleHeight = Math.min(toPos.y, clientHeight) - middleStart;
if (middleHeight > 0.2 * th)
add(0, middleStart, 0, middleHeight);
- if ((!sameLine || !sel.from.ch) && toPos.y < lineSpace.clientHeight - .5 * th)
- add(0, toPos.y, lineSpace.clientWidth - toPos.x, th);
+ if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th)
+ add(0, toPos.y, clientWidth - toPos.x, th);
selectionDiv.innerHTML = html;
cursor.style.display = "none";
selectionDiv.style.display = "";
@@ -1105,7 +1153,12 @@ var CodeMirror = (function() {
if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
// Skip over hidden lines.
- if (from.line != oldFrom) from = skipHidden(from, oldFrom, sel.from.ch);
+ if (from.line != oldFrom) {
+ var from1 = skipHidden(from, oldFrom, sel.from.ch);
+ // If there is no non-hidden line left, force visibility on current line
+ if (!from1) setLineHidden(from.line, false);
+ else from = from1;
+ }
if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
if (posEq(from, to)) sel.inverted = false;
@@ -1114,7 +1167,7 @@ var CodeMirror = (function() {
if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
var head = sel.inverted ? from : to;
- if (head.line != sel.from.line) {
+ if (head.line != sel.from.line && sel.from.line < doc.size) {
var oldLine = getLine(sel.from.line);
if (/^\s+$/.test(oldLine.text))
setTimeout(operation(function() {
@@ -1209,6 +1262,7 @@ var CodeMirror = (function() {
if (unit == "page") dist = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
else if (unit == "line") dist = textHeight();
var target = coordsChar(pos.x, pos.y + dist * dir + 2);
+ if (unit == "page") scroller.scrollTop += localCoords(target, true).y - pos.y;
setCursor(target.line, target.ch, true);
goalColumn = pos.x;
}
@@ -1295,9 +1349,10 @@ var CodeMirror = (function() {
changes.push({from: 0, to: doc.size});
}
function makeTab(col) {
- var w = options.tabSize - col % options.tabSize;
+ var w = options.tabSize - col % options.tabSize, cached = tabCache[w];
+ if (cached) return cached;
for (var str = '<span class="cm-tab">', i = 0; i < w; ++i) str += " ";
- return {html: str + "</span>", width: w};
+ return (tabCache[w] = {html: str + "</span>", width: w});
}
function themeChanged() {
scroller.className = scroller.className.replace(/\s*cm-s-\w+/g, "") +
@@ -1313,7 +1368,7 @@ var CodeMirror = (function() {
var lineN = lineNo(line);
min = Math.min(min, lineN); max = Math.max(max, lineN);
for (var j = 0; j < mk.length; ++j)
- if (mk[j].set == this.set) mk.splice(j--, 1);
+ if (mk[j].marker == this) mk.splice(j--, 1);
}
if (min != Infinity)
changes.push({from: min, to: max + 1});
@@ -1324,7 +1379,7 @@ var CodeMirror = (function() {
var line = this.set[i], mk = line.marked;
for (var j = 0; j < mk.length; ++j) {
var mark = mk[j];
- if (mark.set == this.set) {
+ if (mark.marker == this) {
if (mark.from != null || mark.to != null) {
var found = lineNo(line);
if (found != null) {
@@ -1341,8 +1396,9 @@ var CodeMirror = (function() {
function markText(from, to, className) {
from = clipPos(from); to = clipPos(to);
var tm = new TextMarker();
+ if (!posLess(from, to)) return tm;
function add(line, from, to, className) {
- getLine(line).addMark(new MarkedText(from, to, className, tm.set));
+ getLine(line).addMark(new MarkedText(from, to, className, tm));
}
if (from.line == to.line) add(from.line, from.ch, to.ch, className);
else {
@@ -1362,6 +1418,19 @@ var CodeMirror = (function() {
return bm;
}
+ function findMarksAt(pos) {
+ pos = clipPos(pos);
+ var markers = [], marked = getLine(pos.line).marked;
+ if (!marked) return markers;
+ for (var i = 0, e = marked.length; i < e; ++i) {
+ var m = marked[i];
+ if ((m.from == null || m.from <= pos.ch) &&
+ (m.to == null || m.to >= pos.ch))
+ markers.push(m.marker || m);
+ }
+ return markers;
+ }
+
function addGutterMarker(line, text, className) {
if (typeof line == "number") line = getLine(clipLine(line));
line.gutterMarker = {text: text, style: className};
@@ -1383,10 +1452,11 @@ var CodeMirror = (function() {
else return null;
return line;
}
- function setLineClass(handle, className) {
+ function setLineClass(handle, className, bgClassName) {
return changeLine(handle, function(line) {
- if (line.className != className) {
+ if (line.className != className || line.bgClassName != bgClassName) {
line.className = className;
+ line.bgClassName = bgClassName;
return true;
}
});
@@ -1400,6 +1470,8 @@ var CodeMirror = (function() {
if (hidden && (fline == no || tline == no)) {
var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from;
var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to;
+ // Can't hide the last visible line, we'd have no place to put the cursor
+ if (!to) return;
setSelection(from, to);
}
return (gutterDirty = true);
@@ -1420,7 +1492,7 @@ var CodeMirror = (function() {
}
var marker = line.gutterMarker;
return {line: n, handle: line, text: line.text, markerText: marker && marker.text,
- markerClass: marker && marker.style, lineClass: line.className};
+ markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName};
}
function stringWidth(str) {
@@ -1464,7 +1536,7 @@ var CodeMirror = (function() {
var extra = "";
// Include extra text at the end to make sure the measured line is wrapped in the right way.
if (options.lineWrapping) {
- var end = line.text.indexOf(" ", ch + 2);
+ var end = line.text.indexOf(" ", ch + 6);
extra = htmlEscape(line.text.slice(ch + 1, end < 0 ? line.text.length : end + (ie ? 5 : 0)));
}
measure.innerHTML = "<pre>" + line.getHTML(makeTab, ch) +
@@ -1823,7 +1895,7 @@ var CodeMirror = (function() {
pollInterval: 100,
undoDepth: 40,
tabindex: null,
- document: window.document
+ autofocus: null
};
var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
@@ -1831,7 +1903,7 @@ var CodeMirror = (function() {
var win = /Win/.test(navigator.platform);
// Known modes, by name and by MIME
- var modes = {}, mimeModes = {};
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
CodeMirror.defineMode = function(name, mode) {
if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
modes[name] = mode;
@@ -1842,6 +1914,8 @@ var CodeMirror = (function() {
CodeMirror.resolveMode = function(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
spec = mimeModes[spec];
+ else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
+ return CodeMirror.resolveMode("application/xml");
if (typeof spec == "string") return {name: spec};
else return spec || {name: "null"};
};
@@ -1926,7 +2000,7 @@ var CodeMirror = (function() {
keyMap.basic = {
"Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
"End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
- "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "indentMore", "Shift-Tab": "indentLess",
+ "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "insertTab", "Shift-Tab": "indentAuto",
"Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
};
// Note that the save and find-related commands aren't defined by
@@ -1937,6 +2011,7 @@ var CodeMirror = (function() {
"Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
"Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find",
"Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
fallthrough: "basic"
};
keyMap.macDefault = {
@@ -1945,6 +2020,7 @@ var CodeMirror = (function() {
"Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft",
"Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find",
"Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore",
fallthrough: ["basic", "emacsy"]
};
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
@@ -1987,6 +2063,8 @@ var CodeMirror = (function() {
options.value = textarea.value;
if (!options.tabindex && textarea.tabindex)
options.tabindex = textarea.tabindex;
+ if (options.autofocus == null && textarea.getAttribute("autofocus") != null)
+ options.autofocus = true;
function save() {textarea.value = instance.getValue();}
if (textarea.form) {
@@ -2098,34 +2176,34 @@ var CodeMirror = (function() {
};
CodeMirror.StringStream = StringStream;
- function MarkedText(from, to, className, set) {
- this.from = from; this.to = to; this.style = className; this.set = set;
+ function MarkedText(from, to, className, marker) {
+ this.from = from; this.to = to; this.style = className; this.marker = marker;
}
MarkedText.prototype = {
- attach: function(line) { this.set.push(line); },
+ attach: function(line) { this.marker.set.push(line); },
detach: function(line) {
- var ix = indexOf(this.set, line);
- if (ix > -1) this.set.splice(ix, 1);
+ var ix = indexOf(this.marker.set, line);
+ if (ix > -1) this.marker.set.splice(ix, 1);
},
split: function(pos, lenBefore) {
if (this.to <= pos && this.to != null) return null;
var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore;
var to = this.to == null ? null : this.to - pos + lenBefore;
- return new MarkedText(from, to, this.style, this.set);
+ return new MarkedText(from, to, this.style, this.marker);
},
- dup: function() { return new MarkedText(null, null, this.style, this.set); },
+ dup: function() { return new MarkedText(null, null, this.style, this.marker); },
clipTo: function(fromOpen, from, toOpen, to, diff) {
- if (this.from != null && this.from >= from)
- this.from = Math.max(to, this.from) + diff;
- if (this.to != null && this.to > from)
- this.to = to < this.to ? this.to + diff : from;
if (fromOpen && to > this.from && (to < this.to || this.to == null))
this.from = null;
+ else if (this.from != null && this.from >= from)
+ this.from = Math.max(to, this.from) + diff;
if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null))
this.to = null;
+ else if (this.to != null && this.to > from)
+ this.to = to < this.to ? this.to + diff : from;
},
isDead: function() { return this.from != null && this.to != null && this.from >= this.to; },
- sameSet: function(x) { return this.set == x.set; }
+ sameSet: function(x) { return this.marker == x.marker; }
};
function Bookmark(pos) {
@@ -2168,7 +2246,7 @@ var CodeMirror = (function() {
this.styles = styles || [text, null];
this.text = text;
this.height = 1;
- this.marked = this.gutterMarker = this.className = this.handlers = null;
+ this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null;
this.stateAfter = this.parent = this.hidden = null;
}
Line.inheritMarks = function(text, orig) {
@@ -2214,6 +2292,7 @@ var CodeMirror = (function() {
if (newmark) {
if (!taken.marked) taken.marked = [];
taken.marked.push(newmark); newmark.attach(taken);
+ if (newmark == mark) mk.splice(i--, 1);
}
}
}
@@ -2637,10 +2716,10 @@ var CodeMirror = (function() {
if (start < last.start) {
for (var i = last.start - start - 1; i >= 0; --i)
last.old.unshift(old[i]);
- last.added += last.start - start;
+ oldoff = Math.min(0, added - old.length);
+ last.added += last.start - start + oldoff;
last.start = start;
- }
- else if (last.start < start) {
+ } else if (last.start < start) {
oldoff = start - last.start;
added += oldoff;
}
@@ -2707,19 +2786,21 @@ var CodeMirror = (function() {
var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
- // Detect drag-and-drop
- var dragAndDrop = function() {
- // IE8 has ondragstart and ondrop properties, but doesn't seem to
- // actually support ondragstart the way it's supposed to work.
- if (/MSIE [1-8]\b/.test(navigator.userAgent)) return false;
- var div = document.createElement('div');
- return "draggable" in div;
- }();
-
var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
var ie = /MSIE \d/.test(navigator.userAgent);
var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
var webkit = /WebKit\//.test(navigator.userAgent);
+ var chrome = /Chrome\//.test(navigator.userAgent);
+ var khtml = /KHTML\//.test(navigator.userAgent);
+
+ // Detect drag-and-drop
+ var dragAndDrop = function() {
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
+ // couldn't get it to work yet.
+ if (ie_lt9) return false;
+ var div = document.createElement('div');
+ return "draggable" in div || "dragDrop" in div;
+ }();
var lineSep = "\n";
// Feature-detect whether newlines in textareas are converted to \r\n
@@ -2873,7 +2954,7 @@ var CodeMirror = (function() {
var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
- 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 186: ";", 187: "=", 188: ",",
+ 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 127: "Delete", 186: ";", 187: "=", 188: ",",
189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp",
63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right",
63233: "Down", 63302: "Insert", 63272: "Delete"};
diff --git a/assets/codemirror/javascript.js b/assets/codemirror/javascript.js
index b9388bc..462f486 100644
--- a/assets/codemirror/javascript.js
+++ b/assets/codemirror/javascript.js
@@ -319,8 +319,8 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
kwAllowed: true,
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
- localVars: null,
- context: null,
+ localVars: parserConfig.localVars,
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
indented: 0
};
},
@@ -334,7 +334,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
- state.reAllowed = type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/);
+ state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/));
state.kwAllowed = type != '.';
return parseJS(state, style, type, content, stream);
},

View File

@ -7,6 +7,7 @@
<script src="checkenv.js"></script>
<script src="functiontrace.js"></script>
<script src="../esprima.js"></script>
<script src="../test/3rdparty/esmorph.js"></script>
<script src="../assets/codemirror/codemirror.js"></script>
<script src="../assets/codemirror/javascript.js"></script>
<link rel="stylesheet" type="text/css" href="../assets/codemirror/codemirror.css"/>

View File

@ -61,8 +61,8 @@ function traceRun() {
code = window.editor.getValue();
}
tracer = window.esprima.Tracer.FunctionEntrance('window.TRACE.enterFunction');
code = window.esprima.modify(code, tracer);
tracer = window.esmorph.Tracer.FunctionEntrance('window.TRACE.enterFunction');
code = window.esmorph.modify(code, tracer);
// Enclose in IIFE.
code = '(function() {\n' + code + '\n}())';

168
node_modules/esprima/demo/parse.html generated vendored
View File

@ -9,13 +9,155 @@
<script src="../assets/json2.js"></script>
<script src="../assets/codemirror/codemirror.js"></script>
<script src="../assets/codemirror/javascript.js"></script>
<script src="../assets/yui/yahoo-dom-event.js"></script>
<script src="../assets/yui/treeview-min.js"></script>
<link rel="stylesheet" type="text/css" href="../assets/codemirror/codemirror.css"/>
<link rel="stylesheet" type="text/css" href="../assets/yui/treeview.css"/>
<link rel="stylesheet" type="text/css" href="../assets/style.css"/>
<link rel="stylesheet" type="text/css" href="parse.css"/>
<style>
.ygtvfocus .ygtvlabel,
.ygtvfocus .ygtvlabel:link,
.ygtvfocus .ygtvlabel:visited,
.ygtvfocus .ygtvlabel:hover {
background-color: #eee;
}
table th, table td {
text-align: left;
background-color: white;
}
tbody tr:nth-child(odd) td {
background-color: white;
}
tbody td {
background-color: white;
}
</style>
<script>
/*jslint sloppy:true browser:true */
/*global esprima:true */
/*global esprima:true, YAHOO:true */
var parseId;
function updateTree(syntax) {
if (window.tree) {
window.tree.destroy();
window.tree = null;
}
if (typeof syntax === 'undefined') {
return;
}
if (document.getElementById('tab_tree').className !== 'active') {
return;
}
window.tree = new YAHOO.widget.TreeView("treeview");
document.getElementById('collapse').onclick = function () { window.tree.collapseAll(); };
document.getElementById('expand').onclick = function () { window.tree.expandAll(); };
function isArray(o) {
return (typeof Array.isArray === 'function') ? Array.isArray(o) :
Object.prototype.toString.apply(o) === '[object Array]';
}
function convert(name, node) {
var result, i, key, value, child;
switch (typeof node) {
case 'string':
return {
type: 'Text',
label: name + ': ' + node
};
case 'number':
case 'boolean':
return {
type: 'Text',
label: name + ': ' + String(node)
};
case 'object':
if (!node) {
return {
type: 'Text',
label: name + ': null'
};
}
if (node instanceof RegExp) {
return {
type: 'Text',
label: name + ': ' + node.toString()
};
}
result = {
type: 'Text',
label: name,
expanded: true,
children: []
};
if (isArray(node)) {
if (node.length === 2 && name === 'range') {
result.label = name + ': [' + node[0] + ', ' + node[1] + ']';
} else {
result.label = result.label + ' [' + node.length + ']';
for (i = 0; i < node.length; i += 1) {
key = String(i);
value = node[i];
child = convert(key, value);
if (isArray(child.children) && child.children.length === 1) {
result.children.push(child.children[0]);
} else {
result.children.push(convert(key, value));
}
}
}
} else {
if (typeof node.type !== 'undefined') {
result.children.push({
type: 'Text',
label: node.type,
expanded: true,
children: []
});
for (key in node) {
if (Object.prototype.hasOwnProperty.call(node, key)) {
if (key !== 'type') {
value = node[key];
result.children[0].children.push(convert(key, value));
}
}
}
} else {
for (key in node) {
if (Object.prototype.hasOwnProperty.call(node, key)) {
value = node[key];
result.children.push(convert(key, value));
}
}
}
}
return result;
default:
break;
}
return {
type: 'Text',
label: '?'
};
}
window.tree.buildTreeFromObject(convert('Program body', syntax.body));
window.tree.render();
}
function parse(delay) {
if (parseId) {
window.clearTimeout(parseId);
@ -54,8 +196,10 @@ function parse(delay) {
str = JSON.stringify(result, adjustRegexLiteral, 4);
document.getElementById('tokens').value = JSON.stringify(esprima.parse(code,
{ tokens : true }).tokens, adjustRegexLiteral, 4);
updateTree(result);
} catch (e) {
str = e.toString();
updateTree();
str = e.name + ': ' + e.message;
}
el = document.getElementById('syntax');
@ -66,7 +210,7 @@ function parse(delay) {
}
</script>
</head>
<body>
<body class="yui-skin-sam">
<div class="container">
<div class="topbar">
@ -108,6 +252,15 @@ var answer = 6 * 7;</textarea></p>
<textarea id="tokens" rows="20" readonly></textarea>
</div>
</li>
<li id="tab_tree">
<h3><a id="show_tree">Tree</a></h3>
<div class="tab">
<span style="margin-left: 500px;"><input type="button" id="expand" value="Expand All">
<input type="button" id="collapse" value="Collapse All"></span>
<div id="treeview">
</div>
</div>
</li>
</ul>
</div>
@ -138,12 +291,21 @@ window.onload = function () {
parse(1);
} catch (e) { }
id('show_tree').onclick = function () {
id('tab_tree').className = 'active';
id('tab_syntax').className = '';
id('tab_tokens').className = '';
parse(1);
};
id('show_syntax').onclick = function () {
id('tab_tree').className = '';
id('tab_syntax').className = 'active';
id('tab_tokens').className = '';
};
id('show_tokens').onclick = function () {
id('tab_tree').className = '';
id('tab_syntax').className = '';
id('tab_tokens').className = 'active';
};

120
node_modules/esprima/demo/rewrite.html generated vendored Normal file
View File

@ -0,0 +1,120 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Esprima: Full Source Rewrite Demo</title>
<script src="../test/3rdparty/platform.js"></script>
<script src="../test/3rdparty/escodegen.js"></script>
<script src="checkenv.js"></script>
<script src="rewrite.js"></script>
<script src="../esprima.js"></script>
<script src="../assets/codemirror/codemirror.js"></script>
<script src="../assets/codemirror/javascript.js"></script>
<link rel="stylesheet" type="text/css" href="../assets/codemirror/codemirror.css"/>
<link rel="stylesheet" type="text/css" href="../assets/style.css"/>
<style>
.CodeMirror-scroll {
height: 300px;
}
</style>
</head>
<body>
<div class="container">
<div class="topbar">
<ul class="nav">
<li><a href="../index.html">&larr; Home</a></li>
<li><a href="http://github.com/ariya/esprima">Code</a></li>
<li><a href="http://wiki.esprima.org">Documentation</a></li>
<li><a href="http://issues.esprima.org">Issues</a></li>
</ul>
</div>
<h1>Source Rewrite <small>cleans up and reformats everything</small></h1>
<p>Type ECMAScript code in the editor. Press <b>Rewrite</b> button to get the code
parsed and reconstructed.</p>
<p><textarea id="code" autofocus="autofocus" cols="70" rows="25" spellcheck="false">
// Example of messy code with confusing and inconsistent indentations
function bubbleSort (list) {
var items = list.slice(0), swapped =false,
p, q;
for ( p= 1;p &lt; items.length; ++p) {
for (q=0; q &lt; items.length - p; ++q) {
if (items[q + 1 ] &lt; items[q]) {
swapped =true;
let temp = items[q];
items[q] = items[ q+1]; items[q+1] = temp;
}
}
if (!swapped)
break;
}
return items;
}
</textarea></p>
<p>Indent with:
<label><input type="radio" name="indent" id="onetab" value="onetab"> tab</label>
<label><input type="radio" name="indent" id="twospaces" value="twospaces"> 2 spaces</label>
<label><input checked type="radio" name="indent" id="fourspaces" value="fourspaces"> 4 spaces</label>
</p>
<p><input type="button" value="Rewrite" id="rewrite"></p>
<p id="codemirror" align="right"><small>The above code editor is based on <a href="http://codemirror.net" target="_blank">CodeMirror</a>.</small></p>
<p id="error"></p>
<p><b>Notes</b>:</p>
<ul>
<li>Only valid syntax is accepted.</li>
<li>Comments are <em>not</em> preserved.</li>
<li>It is still experimental (see the <a href="https://github.com/Constellation/escodegen">escodegen project</a>).</li>
</ul>
<p style="margin-top: 50px;">Using Esprima version <span id="version"></span>.</p>
<div class="footer"><strong>Esprima</strong> is created by
<a href="http://ariya.ofilabs.com/about" target="_blank">Ariya Hidayat</a>. Follow <a href="http://twitter.com/ariyahidayat">@ariyahidayat</a> on Twitter.
</div>
<p id="testbox" style="visibility: hidden;"><textarea id="test"></textarea></p>
</div>
<script>
/*jslint sloppy:true browser:true */
/*global sourceRewrite:true, CodeMirror:true */
window.onload = function () {
var el;
el = document.getElementById('version');
if (typeof el.innerText === 'string') {
el.innerText = window.esprima.version;
} else {
el.textContent = window.esprima.version;
}
document.getElementById('rewrite').onclick = sourceRewrite;
};
try {
window.checkEnv();
// This is just testing, to detect whether CodeMirror would fail or not
window.editor = CodeMirror.fromTextArea(document.getElementById("test"));
window.editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true
});
} catch (e) {
// CodeMirror failed to initialize, possible in e.g. old IE.
document.getElementById('codemirror').innerHTML = '';
} finally {
document.getElementById('testbox').parentNode.removeChild(document.getElementById('testbox'));
}
</script>
</body>
</html>

71
node_modules/esprima/demo/rewrite.js generated vendored Normal file
View File

@ -0,0 +1,71 @@
/*
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
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.
*/
/*jslint browser:true evil:true */
function sourceRewrite() {
'use strict';
var code, syntax, indent;
function setText(id, str) {
var el = document.getElementById(id);
if (typeof el.innerText === 'string') {
el.innerText = str;
} else {
el.textContent = str;
}
}
setText('error', '');
if (typeof window.editor !== 'undefined') {
// Using CodeMirror.
code = window.editor.getValue();
} else {
// Plain textarea, likely in a situation where CodeMirror does not work.
code = document.getElementById('code').value;
}
indent = '';
if (document.getElementById('onetab').checked) {
indent = '\t';
} else if (document.getElementById('twospaces').checked) {
indent = ' ';
} else if (document.getElementById('fourspaces').checked) {
indent = ' ';
}
try {
syntax = window.esprima.parse(code, { raw: true });
code = window.escodegen.generate(syntax, { indent: indent });
} catch (e) {
setText('error', e.toString());
} finally {
if (typeof window.editor !== 'undefined') {
window.editor.setValue(code);
} else {
document.getElementById('code').value = code;
}
}
}

1863
node_modules/esprima/esprima.js generated vendored

File diff suppressed because one or more lines are too long

11
node_modules/esprima/index.html generated vendored
View File

@ -25,6 +25,15 @@
(also popularly known as <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a>)
parsing infrastructure for multipurpose analysis. It is also written in ECMAScript.</p>
<p>Esprima serves as a good basis for various tools such as source modification
(<a href="https://github.com/ariya/esmorph">Esmorph</a>), coverage analyzer
(<a href="https://github.com/itay/node-cover">node-cover</a> and
<a href="https://github.com/coveraje/coveraje">coveraje</a>),
source-to-source compiler (<a href="https://github.com/Yoric/Marv-the-Tinker">Marv</a>),
syntax formatter (<a href="https://github.com/fawek/codepainter">Code Painter</a>),
and code generator (<a href="https://github.com/Constellation/escodegen">escodegen</a>).
</p>
<p>Esprima can be used in a web browser:</p>
<pre>&lt;script src="esprima.js"&gt;&lt;script&gt;</pre>
@ -68,11 +77,13 @@ for further info.</p>
<li><a href="demo/precedence.html">Operator precedence</a></li>
<li><a href="demo/collector.html">Regex collector</a></li>
<li><a href="demo/functiontrace.html">Function tracing</a></li>
<li><a href="demo/rewrite.html">Source rewrite</a></li>
</ul>
<h3>Harness tests</h3>
<ul>
<li><a href="test/index.html">Unit tests</a></li>
<li><a href="test/compat.html">Compatibility tests</a></li>
<li><a href="test/coverage.html">Coverage analysis</a></li>
</ul>
<h3>Need for speed</h3>
<ul>

72
node_modules/esprima/package.json generated vendored
View File

@ -1,31 +1,47 @@
{
"name": "esprima",
"description": "ECMAScript parsing infrastructure for multipurpose analysis",
"homepage": "http://esprima.org",
"main": "esprima.js",
"bin": {
"esparse": "./bin/esparse.js"
},
"version": "0.9.8",
"engines": {
"node": ">=0.4.0"
},
"maintainers": [{
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com",
"web": "http://ariya.ofilabs.com"
}],
"repository": {
"type": "git",
"url": "http://github.com/ariya/esprima.git"
},
"licenses": [{
"type": "BSD",
"url": "http://github.com/ariya/esprima/raw/master/LICENSE.BSD"
}],
"scripts": {
"test": "node test/run.js",
"benchmark": "node test/benchmarks.js",
"benchmark-quick": "node test/benchmarks.js quick"
"name": "esprima",
"description": "ECMAScript parsing infrastructure for multipurpose analysis",
"homepage": "http://esprima.org",
"main": "esprima.js",
"bin": {
"esparse": "./bin/esparse.js"
},
"version": "0.9.9",
"engines": {
"node": ">=0.4.0"
},
"maintainers": [
{
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com",
"url": "http://ariya.ofilabs.com"
}
],
"repository": {
"type": "git",
"url": "git://github.com/ariya/esprima.git"
},
"licenses": [
{
"type": "BSD",
"url": "http://github.com/ariya/esprima/raw/master/LICENSE.BSD"
}
],
"scripts": {
"test": "node test/run.js",
"benchmark": "node test/benchmarks.js",
"benchmark-quick": "node test/benchmarks.js quick"
},
"_id": "esprima@0.9.9",
"dependencies": {},
"devDependencies": {},
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.16",
"_nodeVersion": "v0.6.15",
"_defaultsLoaded": true,
"dist": {
"shasum": "cd61f7ed84ab17ed4c34e7bb93765d6e813188ec"
},
"_from": "esprima@0.9.9"
}

906
node_modules/esprima/test/3rdparty/escodegen.js generated vendored Normal file
View File

@ -0,0 +1,906 @@
/*
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
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.
*/
/*jslint bitwise:true */
/*global escodegen:true, exports:true, generateStatement: true*/
(function (exports) {
'use strict';
var Syntax,
Precedence,
BinaryPrecedence,
base,
indent,
extra,
parse;
Syntax = {
AssignmentExpression: 'AssignmentExpression',
ArrayExpression: 'ArrayExpression',
BlockStatement: 'BlockStatement',
BinaryExpression: 'BinaryExpression',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DoWhileStatement: 'DoWhileStatement',
DebuggerStatement: 'DebuggerStatement',
EmptyStatement: 'EmptyStatement',
ExpressionStatement: 'ExpressionStatement',
ForStatement: 'ForStatement',
ForInStatement: 'ForInStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
Identifier: 'Identifier',
IfStatement: 'IfStatement',
Literal: 'Literal',
LabeledStatement: 'LabeledStatement',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
Program: 'Program',
Property: 'Property',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SwitchStatement: 'SwitchStatement',
SwitchCase: 'SwitchCase',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TryStatement: 'TryStatement',
UnaryExpression: 'UnaryExpression',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement'
};
Precedence = {
Sequence: 0,
Assignment: 1,
Conditional: 2,
LogicalOR: 3,
LogicalAND: 4,
LogicalXOR: 5,
BitwiseOR: 6,
BitwiseAND: 7,
Equality: 8,
Relational: 9,
BitwiseSHIFT: 10,
Additive: 11,
Multiplicative: 12,
Unary: 13,
Postfix: 14,
Call: 15,
New: 16,
Member: 17,
Primary: 18
};
BinaryPrecedence = {
'||': Precedence.LogicalOR,
'&&': Precedence.LogicalAND,
'^': Precedence.LogicalXOR,
'|': Precedence.BitwiseOR,
'&': Precedence.BitwiseAND,
'==': Precedence.Equality,
'!=': Precedence.Equality,
'===': Precedence.Equality,
'!==': Precedence.Equality,
'<': Precedence.Relational,
'>': Precedence.Relational,
'<=': Precedence.Relational,
'>=': Precedence.Relational,
'in': Precedence.Relational,
'instanceof': Precedence.Relational,
'<<': Precedence.BitwiseSHIFT,
'>>': Precedence.BitwiseSHIFT,
'>>>': Precedence.BitwiseSHIFT,
'+': Precedence.Additive,
'-': Precedence.Additive,
'*': Precedence.Multiplicative,
'%': Precedence.Multiplicative,
'/': Precedence.Multiplicative
};
function getDefaultOptions() {
// default options
return {
indent: null,
base: null,
parse: null,
format: {
indent: {
style: ' ',
base: 0
}
}
};
}
function unicodeEscape(ch) {
var result, i;
result = ch.charCodeAt(0).toString(16);
for (i = result.length; i < 4; i += 1) {
result = '0' + result;
}
return '\\u' + result;
}
function stringToArray(str) {
var length = str.length,
result = [],
i;
for (i = 0; i < length; i += 1) {
result[i] = str.charAt(i);
}
return result;
}
function stringRepeat(str, num) {
var result = '';
for (num |= 0; num > 0; num >>>= 1, str += str) {
if (num & 1) {
result += str;
}
}
return result;
}
function updateDeeply(target, override) {
var key, val;
function isHashObject(target) {
return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp);
}
for (key in override) {
if (override.hasOwnProperty(key)) {
val = override[key];
if (isHashObject(val)) {
if (isHashObject(target[key])) {
updateDeeply(target[key], val);
} else {
target[key] = updateDeeply({}, val);
}
} else {
target[key] = val;
}
}
}
return target;
}
function escapeString(str) {
var result = '', i, len, ch;
if (typeof str[0] === 'undefined') {
str = stringToArray(str);
}
for (i = 0, len = str.length; i < len; i += 1) {
ch = str[i];
if ('\'\\\b\f\n\r\t'.indexOf(ch) >= 0) {
result += '\\';
switch (ch) {
case '\'':
result += '\'';
break;
case '\\':
result += '\\';
break;
case '\b':
result += 'b';
break;
case '\f':
result += 'f';
break;
case '\n':
result += 'n';
break;
case '\r':
result += 'r';
break;
case '\t':
result += 't';
break;
}
} else if (ch < ' ' || ch.charCodeAt(0) >= 0x80) {
result += unicodeEscape(ch);
} else {
result += ch;
}
}
return '\'' + result + '\'';
}
function addIndent(stmt) {
return base + stmt;
}
function parenthesize(text, current, should) {
return (current < should) ? '(' + text + ')' : text;
}
function maybeBlock(stmt, suffix) {
var previousBase, result;
if (stmt.type === Syntax.BlockStatement) {
result = ' ' + generateStatement(stmt);
if (suffix) {
return result + ' ';
}
return result;
}
if (stmt.type === Syntax.EmptyStatement) {
result = ';';
} else {
previousBase = base;
base += indent;
result = '\n' + addIndent(generateStatement(stmt));
base = previousBase;
}
if (suffix) {
return result + '\n' + addIndent('');
}
return result;
}
function generateFunctionBody(node) {
var result, i, len;
result = '(';
for (i = 0, len = node.params.length; i < len; i += 1) {
result += node.params[i].name;
if ((i + 1) < len) {
result += ', ';
}
}
return result + ')' + maybeBlock(node.body);
}
function generateExpression(expr, precedence) {
var result, currentPrecedence, previousBase, i, len, raw;
if (!precedence) {
precedence = Precedence.Sequence;
}
switch (expr.type) {
case Syntax.SequenceExpression:
result = '';
for (i = 0, len = expr.expressions.length; i < len; i += 1) {
result += generateExpression(expr.expressions[i], Precedence.Assignment);
if ((i + 1) < len) {
result += ', ';
}
}
result = parenthesize(result, Precedence.Sequence, precedence);
break;
case Syntax.AssignmentExpression:
result = parenthesize(
generateExpression(expr.left, Precedence.Call) + ' ' + expr.operator + ' ' +
generateExpression(expr.right, Precedence.Assignment),
Precedence.Assignment,
precedence
);
break;
case Syntax.ConditionalExpression:
result = parenthesize(
generateExpression(expr.test, Precedence.LogicalOR) + ' ? ' +
generateExpression(expr.consequent, Precedence.Assignment) + ' : ' +
generateExpression(expr.alternate, Precedence.Assignment),
Precedence.Conditional,
precedence
);
break;
case Syntax.LogicalExpression:
case Syntax.BinaryExpression:
currentPrecedence = BinaryPrecedence[expr.operator];
result = generateExpression(expr.left, currentPrecedence) +
' ' + expr.operator + ' ' +
generateExpression(expr.right, currentPrecedence + 1);
if (expr.operator === 'in') {
// TODO parenthesize only in allowIn = false case
result = '(' + result + ')';
} else {
result = parenthesize(result, currentPrecedence, precedence);
}
break;
case Syntax.CallExpression:
result = '';
for (i = 0, len = expr['arguments'].length; i < len; i += 1) {
result += generateExpression(expr['arguments'][i], Precedence.Assignment);
if ((i + 1) < len) {
result += ', ';
}
}
result = parenthesize(
generateExpression(expr.callee, Precedence.Call) + '(' + result + ')',
Precedence.Call,
precedence
);
break;
case Syntax.NewExpression:
result = '';
for (i = 0, len = expr['arguments'].length; i < len; i += 1) {
result += generateExpression(expr['arguments'][i], Precedence.Assignment);
if ((i + 1) < len) {
result += ', ';
}
}
result = parenthesize(
'new ' + generateExpression(expr.callee, Precedence.New) + '(' + result + ')',
Precedence.New,
precedence
);
break;
case Syntax.MemberExpression:
result = generateExpression(expr.object, Precedence.Call);
if (expr.computed) {
result += '[' + generateExpression(expr.property) + ']';
} else {
if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') {
if (result.indexOf('.') < 0) {
if (!/[eExX]/.test(result) && !(result.length >= 2 && result[0] === '0')) {
result += '.';
}
}
}
result += '.' + expr.property.name;
}
result = parenthesize(result, Precedence.Member, precedence);
break;
case Syntax.UnaryExpression:
result = expr.operator;
if (result.length > 2) {
result += ' ';
}
result = parenthesize(
result + generateExpression(expr.argument, Precedence.Unary +
(
expr.argument.type === Syntax.UnaryExpression &&
expr.operator.length < 3 &&
expr.argument.operator === expr.operator ? 1 : 0
)
),
Precedence.Unary,
precedence
);
break;
case Syntax.UpdateExpression:
if (expr.prefix) {
result = parenthesize(
expr.operator +
generateExpression(expr.argument, Precedence.Unary),
Precedence.Unary,
precedence
);
} else {
result = parenthesize(
generateExpression(expr.argument, Precedence.Postfix) +
expr.operator,
Precedence.Postfix,
precedence
);
}
break;
case Syntax.FunctionExpression:
result = 'function ';
if (expr.id) {
result += expr.id.name;
}
result += generateFunctionBody(expr);
break;
case Syntax.ArrayExpression:
if (!expr.elements.length) {
result = '[]';
break;
}
result = '[\n';
previousBase = base;
base += indent;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
if (!expr.elements[i]) {
result += addIndent('');
if ((i + 1) === len) {
result += ',';
}
} else {
result += addIndent(generateExpression(expr.elements[i], Precedence.Assignment));
}
if ((i + 1) < len) {
result += ',\n';
}
}
base = previousBase;
result += '\n' + addIndent(']');
break;
case Syntax.Property:
if (expr.kind === 'get' || expr.kind === 'set') {
result = expr.kind + ' ' + generateExpression(expr.key) +
generateFunctionBody(expr.value);
} else {
result = generateExpression(expr.key) + ': ' +
generateExpression(expr.value, Precedence.Assignment);
}
break;
case Syntax.ObjectExpression:
if (!expr.properties.length) {
result = '{}';
break;
}
result = '{\n';
previousBase = base;
base += indent;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
result += addIndent(generateExpression(expr.properties[i]));
if ((i + 1) < len) {
result += ',\n';
}
}
base = previousBase;
result += '\n' + addIndent('}');
break;
case Syntax.ThisExpression:
result = 'this';
break;
case Syntax.Identifier:
result = expr.name;
break;
case Syntax.Literal:
if (expr.hasOwnProperty('raw') && parse) {
try {
raw = parse(expr.raw).body[0].expression;
if (raw.type === Syntax.Literal) {
if (raw.value === expr.value) {
result = expr.raw;
break;
}
}
} catch (e) {
// not use raw property
}
}
if (expr.value === null) {
result = 'null';
break;
}
if (typeof expr.value === 'string') {
result = escapeString(expr.value);
break;
}
if (typeof expr.value === 'number' && expr.value === Infinity) {
// Infinity is variable
result = '1e+1000';
break;
}
result = expr.value.toString();
break;
default:
break;
}
if (result === undefined) {
throw new Error('Unknown expression type: ' + expr.type);
}
return result;
}
function generateStatement(stmt) {
var i, len, result, previousBase;
switch (stmt.type) {
case Syntax.BlockStatement:
result = '{\n';
previousBase = base;
base += indent;
for (i = 0, len = stmt.body.length; i < len; i += 1) {
result += addIndent(generateStatement(stmt.body[i])) + '\n';
}
base = previousBase;
result += addIndent('}');
break;
case Syntax.BreakStatement:
if (stmt.label) {
result = 'break ' + stmt.label.name + ';';
} else {
result = 'break;';
}
break;
case Syntax.ContinueStatement:
if (stmt.label) {
result = 'continue ' + stmt.label.name + ';';
} else {
result = 'continue;';
}
break;
case Syntax.DoWhileStatement:
result = 'do' + maybeBlock(stmt.body, true) + 'while (' + generateExpression(stmt.test) + ');';
break;
case Syntax.CatchClause:
previousBase = base;
base += indent;
result = ' catch (' + generateExpression(stmt.param) + ')';
base = previousBase;
result += maybeBlock(stmt.body);
break;
case Syntax.DebuggerStatement:
result = 'debugger;';
break;
case Syntax.EmptyStatement:
result = ';';
break;
case Syntax.ExpressionStatement:
result = generateExpression(stmt.expression);
// 12.4 '{', 'function' is not allowed in this position.
// wrap espression with parentheses
if (result[0] === '{' || result.indexOf('function ') === 0) {
result = '(' + result + ');';
} else {
result += ';';
}
break;
case Syntax.VariableDeclarator:
if (stmt.init) {
result = stmt.id.name + ' = ' + generateExpression(stmt.init, Precedence.Assignment);
} else {
result = stmt.id.name;
}
break;
case Syntax.VariableDeclaration:
result = stmt.kind + ' ';
// special path for
// var x = function () {
// };
if (stmt.declarations.length === 1 && stmt.declarations[0].init &&
stmt.declarations[0].init.type === Syntax.FunctionExpression) {
result += generateStatement(stmt.declarations[0]);
} else {
previousBase = base;
base += indent;
for (i = 0, len = stmt.declarations.length; i < len; i += 1) {
result += generateStatement(stmt.declarations[i]);
if ((i + 1) < len) {
result += ', ';
}
}
base = previousBase;
}
result += ';';
break;
case Syntax.ThrowStatement:
result = 'throw ' + generateExpression(stmt.argument) + ';';
break;
case Syntax.TryStatement:
result = 'try' + maybeBlock(stmt.block);
for (i = 0, len = stmt.handlers.length; i < len; i += 1) {
result += generateStatement(stmt.handlers[i]);
}
if (stmt.finalizer) {
result += ' finally' + maybeBlock(stmt.finalizer);
}
break;
case Syntax.SwitchStatement:
previousBase = base;
base += indent;
result = 'switch (' + generateExpression(stmt.discriminant) + ') {\n';
base = previousBase;
if (stmt.cases) {
for (i = 0, len = stmt.cases.length; i < len; i += 1) {
result += addIndent(generateStatement(stmt.cases[i])) + '\n';
}
}
result += addIndent('}');
break;
case Syntax.SwitchCase:
previousBase = base;
base += indent;
if (stmt.test) {
result = 'case ' + generateExpression(stmt.test) + ':';
} else {
result = 'default:';
}
i = 0;
len = stmt.consequent.length;
if (len && stmt.consequent[0].type === Syntax.BlockStatement) {
result += maybeBlock(stmt.consequent[0]);
i = 1;
}
for (; i < len; i += 1) {
result += '\n' + addIndent(generateStatement(stmt.consequent[i]));
}
base = previousBase;
break;
case Syntax.IfStatement:
if (stmt.alternate) {
if (stmt.alternate.type === Syntax.IfStatement) {
previousBase = base;
base += indent;
result = 'if (' + generateExpression(stmt.test) + ')';
base = previousBase;
result += maybeBlock(stmt.consequent, true) + 'else ' + generateStatement(stmt.alternate);
} else {
previousBase = base;
base += indent;
result = 'if (' + generateExpression(stmt.test) + ')';
base = previousBase;
result += maybeBlock(stmt.consequent, true) + 'else' + maybeBlock(stmt.alternate);
}
} else {
previousBase = base;
base += indent;
result = 'if (' + generateExpression(stmt.test) + ')';
base = previousBase;
result += maybeBlock(stmt.consequent);
}
break;
case Syntax.ForStatement:
previousBase = base;
base += indent;
result = 'for (';
if (stmt.init) {
if (stmt.init.type === Syntax.VariableDeclaration) {
result += generateStatement(stmt.init);
} else {
result += generateExpression(stmt.init) + ';';
}
} else {
result += ';';
}
if (stmt.test) {
result += ' ' + generateExpression(stmt.test) + ';';
} else {
result += ';';
}
if (stmt.update) {
result += ' ' + generateExpression(stmt.update) + ')';
} else {
result += ')';
}
base = previousBase;
result += maybeBlock(stmt.body);
break;
case Syntax.ForInStatement:
result = 'for (';
if (stmt.left.type === Syntax.VariableDeclaration) {
previousBase = base;
base += indent + indent;
result += stmt.left.kind + ' ' + generateStatement(stmt.left.declarations[0]);
base = previousBase;
} else {
previousBase = base;
base += indent;
result += generateExpression(stmt.left, Precedence.Call);
base = previousBase;
}
previousBase = base;
base += indent;
result += ' in ' + generateExpression(stmt.right) + ')';
base = previousBase;
result += maybeBlock(stmt.body);
break;
case Syntax.LabeledStatement:
result = stmt.label.name + ':' + maybeBlock(stmt.body);
break;
case Syntax.Program:
result = '';
for (i = 0, len = stmt.body.length; i < len; i += 1) {
result += generateStatement(stmt.body[i]);
if ((i + 1) < len) {
result += '\n';
}
}
break;
case Syntax.FunctionDeclaration:
result = 'function ';
if (stmt.id) {
result += stmt.id.name;
}
result += generateFunctionBody(stmt);
break;
case Syntax.ReturnStatement:
if (stmt.argument) {
result = 'return ' + generateExpression(stmt.argument) + ';';
} else {
result = 'return;';
}
break;
case Syntax.WhileStatement:
previousBase = base;
base += indent;
result = 'while (' + generateExpression(stmt.test) + ')';
base = previousBase;
result += maybeBlock(stmt.body);
break;
case Syntax.WithStatement:
previousBase = base;
base += indent;
result = 'with (' + generateExpression(stmt.object) + ')';
base = previousBase;
result += maybeBlock(stmt.body);
break;
default:
break;
}
if (result === undefined) {
throw new Error('Unknown statement type: ' + stmt.type);
}
return result;
}
function generate(node, options) {
var defaultOptions = getDefaultOptions();
if (typeof options !== 'undefined') {
// Obsolete options
//
// `options.indent`
// `options.base`
//
// Instead of them, we can use `option.format.indent`.
if (typeof options.indent === 'string') {
defaultOptions.format.style = options.indent;
}
options = updateDeeply(defaultOptions, options);
indent = options.format.style;
if (typeof options.base === 'string') {
base = options.base;
} else {
base = stringRepeat(indent, options.format.base);
}
parse = options.parse;
} else {
options = defaultOptions;
indent = options.format.style;
base = stringRepeat(indent, options.format.base);
parse = options.parse;
}
switch (node.type) {
case Syntax.BlockStatement:
case Syntax.BreakStatement:
case Syntax.CatchClause:
case Syntax.ContinueStatement:
case Syntax.DoWhileStatement:
case Syntax.DebuggerStatement:
case Syntax.EmptyStatement:
case Syntax.ExpressionStatement:
case Syntax.ForStatement:
case Syntax.ForInStatement:
case Syntax.FunctionDeclaration:
case Syntax.IfStatement:
case Syntax.LabeledStatement:
case Syntax.Program:
case Syntax.ReturnStatement:
case Syntax.SwitchStatement:
case Syntax.SwitchCase:
case Syntax.ThrowStatement:
case Syntax.TryStatement:
case Syntax.VariableDeclaration:
case Syntax.VariableDeclarator:
case Syntax.WhileStatement:
case Syntax.WithStatement:
return generateStatement(node);
case Syntax.AssignmentExpression:
case Syntax.ArrayExpression:
case Syntax.BinaryExpression:
case Syntax.CallExpression:
case Syntax.ConditionalExpression:
case Syntax.FunctionExpression:
case Syntax.Identifier:
case Syntax.Literal:
case Syntax.LogicalExpression:
case Syntax.MemberExpression:
case Syntax.NewExpression:
case Syntax.ObjectExpression:
case Syntax.Property:
case Syntax.SequenceExpression:
case Syntax.ThisExpression:
case Syntax.UnaryExpression:
case Syntax.UpdateExpression:
return generateExpression(node);
default:
break;
}
throw new Error('Unknown node type: ' + node.type);
}
// Sync with package.json.
exports.version = '0.0.3-dev';
exports.generate = generate;
}(typeof exports === 'undefined' ? (escodegen = {}) : exports));
/* vim: set sw=4 ts=4 et tw=80 : */

240
node_modules/esprima/test/3rdparty/esmorph.js generated vendored Normal file
View File

@ -0,0 +1,240 @@
/*
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
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.
*/
/*jslint node:true browser:true */
/*global esmorph:true,esprima:true */
(function (exports) {
'use strict';
var Syntax = {
AssignmentExpression: 'AssignmentExpression',
ArrayExpression: 'ArrayExpression',
BlockStatement: 'BlockStatement',
BinaryExpression: 'BinaryExpression',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DoWhileStatement: 'DoWhileStatement',
DebuggerStatement: 'DebuggerStatement',
EmptyStatement: 'EmptyStatement',
ExpressionStatement: 'ExpressionStatement',
ForStatement: 'ForStatement',
ForInStatement: 'ForInStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
Identifier: 'Identifier',
IfStatement: 'IfStatement',
Literal: 'Literal',
LabeledStatement: 'LabeledStatement',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
Program: 'Program',
Property: 'Property',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SwitchStatement: 'SwitchStatement',
SwitchCase: 'SwitchCase',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TryStatement: 'TryStatement',
UnaryExpression: 'UnaryExpression',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement'
};
// Executes visitor on the object and its children (recursively).
function traverse(object, visitor, master) {
var key, child, parent, path;
parent = (typeof master === 'undefined') ? [] : master;
if (visitor.call(null, object, parent) === false) {
return;
}
for (key in object) {
if (object.hasOwnProperty(key)) {
child = object[key];
path = [ object ];
path.push(parent);
if (typeof child === 'object' && child !== null) {
traverse(child, visitor, path);
}
}
}
}
// Insert a prolog in the body of every function.
// It will be in the form of a function call:
//
// traceName(object);
//
// where the object contains the following properties:
//
// 'name' holds the name of the function
// 'lineNumber' holds the starting line number of the function block
// 'range' contains the index-based range of the function
//
// The name of the function represents the associated reference for
// the function (deduced on a best-effort basis if it is not
// a function declaration).
//
// If traceName is a function instead of a string, it will be invoked and
// the result will be used as the entire prolog. The arguments for the
// invocation are the function name, range, and location info.
function traceFunctionEntrance(traceName) {
return function (code) {
var tree,
functionList,
param,
signature,
pos,
i;
tree = esprima.parse(code, { range: true, loc: true });
functionList = [];
traverse(tree, function (node, path) {
var parent;
if (node.type === Syntax.FunctionDeclaration) {
functionList.push({
name: node.id.name,
range: node.range,
loc: node.loc,
blockStart: node.body.range[0]
});
} else if (node.type === Syntax.FunctionExpression) {
parent = path[0];
if (parent.type === Syntax.AssignmentExpression) {
if (typeof parent.left.range !== 'undefined') {
functionList.push({
name: code.slice(parent.left.range[0],
parent.left.range[1] + 1),
range: node.range,
loc: node.loc,
blockStart: node.body.range[0]
});
}
} else if (parent.type === Syntax.VariableDeclarator) {
functionList.push({
name: parent.id.name,
range: node.range,
loc: node.loc,
blockStart: node.body.range[0]
});
} else if (parent.type === Syntax.CallExpression) {
functionList.push({
name: parent.id ? parent.id.name : '[Anonymous]',
range: node.range,
loc: node.loc,
blockStart: node.body.range[0]
});
} else if (typeof parent.length === 'number') {
functionList.push({
name: parent.id ? parent.id.name : '[Anonymous]',
range: node.range,
loc: node.loc,
blockStart: node.body.range[0]
});
} else if (typeof parent.key !== 'undefined') {
if (parent.key.type === 'Identifier') {
if (parent.value === node && parent.key.name) {
functionList.push({
name: parent.key.name,
range: node.range,
loc: node.loc,
blockStart: node.body.range[0]
});
}
}
}
}
});
// Insert the instrumentation code from the last entry.
// This is to ensure that the range for each entry remains valid)
// (it won't shift due to some new inserting string before the range).
for (i = functionList.length - 1; i >= 0; i -= 1) {
param = {
name: functionList[i].name,
range: functionList[i].range,
loc: functionList[i].loc
};
if (typeof traceName === 'function') {
signature = traceName.call(null, param);
} else {
signature = traceName + '({ ';
signature += 'name: \'' + functionList[i].name + '\', ';
if (typeof functionList[i].loc !== 'undefined') {
signature += 'lineNumber: ' + functionList[i].loc.start.line + ', ';
}
signature += 'range: [' + functionList[i].range[0] + ', ' +
functionList[i].range[1] + '] ';
signature += '});';
}
pos = functionList[i].blockStart + 1;
code = code.slice(0, pos) + '\n' + signature + code.slice(pos, code.length);
}
return code;
};
}
function modify(code, modifiers) {
var i;
if (Object.prototype.toString.call(modifiers) === '[object Array]') {
for (i = 0; i < modifiers.length; i += 1) {
code = modifiers[i].call(null, code);
}
} else if (typeof modifiers === 'function') {
code = modifiers.call(null, code);
} else {
throw new Error('Wrong use of esmorph.modify() function');
}
return code;
}
// Sync with package.json.
exports.version = '0.0.0-dev';
exports.modify = modify;
exports.Tracer = {
FunctionEntrance: traceFunctionEntrance
};
}(typeof exports === 'undefined' ? (esmorph = {}) : exports));

View File

@ -1,61 +1,59 @@
/*!
* Platform.js <http://mths.be/platform>
* Copyright 2010-2011 John-David Dalton <http://allyoucanleet.com/>
* Platform.js v1.0.0-pre <http://mths.be/platform>
* Copyright 2010-2012 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit>
*/
;(function(window) {
/** Backup possible window/global object */
var oldWin = window,
/** Possible global object */
thisBinding = this,
var oldWin = window;
/** Detect free variable `exports` */
freeExports = typeof exports == 'object' && exports,
var freeExports = typeof exports == 'object' && exports;
/** Detect free variable `global` */
freeGlobal = typeof global == 'object' && global && (global == global.global ? (window = global) : global),
var freeGlobal = typeof global == 'object' && global &&
(global == global.global ? (window = global) : global);
/** Used to check for own properties of an object */
hasOwnProperty = {}.hasOwnProperty,
/** Opera regexp */
var reOpera = /Opera/;
/** Used to resolve a value's internal [[Class]] */
toString = {}.toString,
var toString = {}.toString;
/** Detect Java environment */
java = /Java/.test(getClassOf(window.java)) && window.java,
var java = /Java/.test(getClassOf(window.java)) && window.java;
/** A character to represent alpha */
alpha = java ? 'a' : '\u03b1',
var alpha = java ? 'a' : '\u03b1';
/** A character to represent beta */
beta = java ? 'b' : '\u03b2',
var beta = java ? 'b' : '\u03b2';
/** Browser document object */
doc = window.document || {},
var doc = window.document || {};
/** Used to check for own properties of an object */
var hasOwnProperty = {}.hasOwnProperty;
/** Browser navigator object */
nav = window.navigator || {},
/** Previous platform object */
old = window.platform,
/** Browser user agent string */
userAgent = nav.userAgent || '',
var nav = window.navigator || {};
/**
* Detect Opera browser
* http://www.howtocreate.co.uk/operaStuff/operaObject.html
* http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini
*/
opera = window.operamini || window.opera,
/** Opera regexp */
reOpera = /Opera/,
var opera = window.operamini || window.opera;
/** Opera [[Class]] */
operaClass = reOpera.test(operaClass = getClassOf(opera)) ? operaClass : (opera = null);
var operaClass = reOpera.test(operaClass = getClassOf(opera)) ? operaClass : (opera = null);
/** Possible global object */
var thisBinding = this;
/** Browser user agent string */
var userAgent = nav.userAgent || '';
/*--------------------------------------------------------------------------*/
@ -175,7 +173,17 @@
}
/**
* A bare-bones` Array#reduce` utility function.
* Prepares a string for use in a RegExp constructor by making hyphens and spaces optional.
* @private
* @param {String} string The string to qualify.
* @returns {String} The qualified string.
*/
function qualify(string) {
return String(string).replace(/([ -])(?!$)/g, '$1?');
}
/**
* A bare-bones` Array#reduce` like utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
@ -190,16 +198,6 @@
return accumulator;
}
/**
* Prepares a string for use in a RegExp constructor by making hyphens and spaces optional.
* @private
* @param {String} string The string to qualify.
* @returns {String} The qualified string.
*/
function qualify(string) {
return String(string).replace(/([ -])(?!$)/g, '$1?');
}
/**
* Removes leading and trailing whitespace from a string.
* @private
@ -223,25 +221,25 @@
ua || (ua = userAgent);
/** Temporary variable used over the script's lifetime */
var data,
var data;
/** The CPU architecture */
arch = ua,
var arch = ua;
/** Platform description array */
description = [],
var description = [];
/** Platform alpha/beta indicator */
prerelease = null,
var prerelease = null;
/** A flag to indicate that environment features should be used to resolve the platform */
useFeatures = ua == userAgent,
var useFeatures = ua == userAgent;
/** The browser/environment version */
version = useFeatures && opera && typeof opera.version == 'function' && opera.version(),
var version = useFeatures && opera && typeof opera.version == 'function' && opera.version();
/* Detectable layout engines (order is important) */
layout = getLayout([
var layout = getLayout([
{ 'label': 'WebKit', 'pattern': 'AppleWebKit' },
'iCab',
'Presto',
@ -250,10 +248,10 @@
'Trident',
'KHTML',
'Gecko'
]),
]);
/* Detectable browser names (order is important) */
name = getName([
var name = getName([
'Adobe AIR',
'Arora',
'Avant Browser',
@ -289,10 +287,10 @@
{ 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' },
{ 'label': 'IE', 'pattern': 'MSIE' },
'Safari'
]),
]);
/* Detectable products (order is important) */
product = getProduct([
var product = getProduct([
'BlackBerry',
{ 'label': 'Galaxy S', 'pattern': 'GT-I9000' },
{ 'label': 'Galaxy S2', 'pattern': 'GT-I9100' },
@ -306,10 +304,10 @@
'TouchPad',
'Transformer',
'Xoom'
]),
]);
/* Detectable manufacturers */
manufacturer = getManufacturer({
var manufacturer = getManufacturer({
'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 },
'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 },
'Asus': { 'Transformer': 1 },
@ -320,10 +318,10 @@
'Motorola': { 'Xoom': 1 },
'Nokia': { },
'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1 }
}),
});
/* Detectable OSes (order is important) */
os = getOS([
var os = getOS([
'Android',
'CentOS',
'Debian',
@ -489,17 +487,6 @@
/*------------------------------------------------------------------------*/
/**
* Restores a previously overwritten platform object.
* @memberOf platform
* @type Function
* @returns {Object} The current platform object.
*/
function noConflict() {
window['platform'] = old;
return this;
}
/**
* Return platform description when the platform object is coerced to a string.
* @name toString
@ -542,8 +529,9 @@
}
// detect false positives for Firefox/Safari
else if (!name || (data = !/\bMinefield\b/i.test(ua) && /Firefox|Safari/.exec(name))) {
// clear name of false positives
if (name && !product && /[/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) {
// escape the `/` for Firefox 1
if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) {
// clear name of false positives
name = null;
}
// reassign a generic name
@ -716,8 +704,10 @@
}
// detect WebKit Nightly and approximate Chrome/Safari versions
if ((data = (/AppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) {
// correct build for numeric comparison
// (e.g. "532.5" becomes "532.05")
data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data];
// nightly builds are postfixed with a `+`
data = [parseFloat(data), data];
if (name == 'Safari' && data[1].slice(-1) == '+') {
name = 'WebKit Nightly';
prerelease = 'alpha';
@ -738,7 +728,7 @@
data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : '5');
} else {
layout[1] = 'like Chrome';
data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.5 ? 3 : data < 533 ? 4 : data < 534.3 ? 5 : data < 534.7 ? 6 : data < 534.1 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.3 ? 11 : data < 535.1 ? 12 : data < 535.2 ? '13+' : data < 535.5 ? 15 : data < 535.7 ? 16 : '17');
data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 535.21 ? 18 : '19');
}
// add the postfix of ".x" or "+" for approximate versions
layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+');
@ -856,9 +846,6 @@
*/
'ua': ua,
// avoid platform object conflicts in browsers
'noConflict': noConflict,
// parses a user agent string into a platform object
'parse': parse,
@ -876,7 +863,7 @@
freeExports[key] = value;
});
}
// via curl.js or RequireJS
// via an AMD loader
else if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
define('platform', function() {
return parse();

View File

@ -9,30 +9,6 @@
<script src="compare.js"></script>
<script src="3rdparty/benchmark.js"></script>
<script src="3rdparty/XMLHttpRequest.js"></script>
<!-- Mozilla Narcissus -->
<script src="3rdparty/jsdefs.js"></script>
<script src="3rdparty/jslex.js"></script>
<script src="3rdparty/jsparse.js"></script>
<!-- ZeParser (https://github.com/qfox/ZeParser) -->
<script src="3rdparty/Tokenizer.js"></script>
<script src="3rdparty/ZeParser.js"></script>
<!-- parse-js, part of UglifyJS -->
<script>
/*global exports: true, window: true*/
exports = window.parseJS = {};
</script>
<script src="3rdparty/parse-js.js"></script>
<script>
/*global runBenchmarks: true*/
window.onload = function () {
'use strict';
window.setTimeout(runBenchmarks, 211);
};
</script>
</head>
<body>
@ -111,7 +87,7 @@ window.onload = function () {
</tbody>
</table>
<p><strong>Warning:</strong> Since each parser has a different format for the syntax tree, the speed is not fully comparable (the cost of constructing different result is not taken into account). These tests exist only to ensure that Esprima parser is not ridiculously slow, e.g. one magnitude slower compare to other parsers.</p>
<p><strong>Warning:</strong> Since each parser has a different format for the syntax tree, the speed is not fully comparable (the cost of constructing different result is not taken into account). These tests exist only to ensure that Esprima parser is not ridiculously slow compare to other parsers.</p>
<p><strong>parse-js</strong> is the parser used in <a href="https://github.com/mishoo/UglifyJS">UglifyJS</a>. It's a JavaScript port of the Common LISP version. This test uses <code>parse-js</code> from UglifyJS version 1.2.5 (Jan 13 2011).</p>
@ -124,6 +100,40 @@ window.onload = function () {
<a href="http://ariya.ofilabs.com/about" target="_blank">Ariya Hidayat</a>. Follow <a href="http://twitter.com/ariyahidayat">@ariyahidayat</a> on Twitter.
</div>
</div>
<script>
/*jslint sloppy:true, browser:true */
/*global runBenchmarks: true, exports: true */
window.onload = function () {
function inject(fname) {
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script');
script.src = fname;
script.type = 'text/javascript';
head.appendChild(script);
}
// Mozilla Narcissus
if (typeof Object.create === 'function' && typeof Object.defineProperty === 'function') {
inject('3rdparty/jsdefs.js');
inject('3rdparty/jslex.js');
inject('3rdparty/jsparse.js');
}
window.setTimeout(runBenchmarks, 211);
};
</script>
<!-- ZeParser (https://github.com/qfox/ZeParser) -->
<script src="3rdparty/Tokenizer.js"></script>
<script src="3rdparty/ZeParser.js"></script>
<!-- parse-js, part of UglifyJS -->
<script>
exports = window.parseJS = {};
</script>
<script src="3rdparty/parse-js.js"></script>
</body>
</html>

26
node_modules/esprima/test/compare.js generated vendored
View File

@ -154,14 +154,16 @@ function runBenchmarks() {
function runBenchmark() {
var test, source, parser, fn, benchmark;
function formatTime(t) {
return (t === 0) ? 'N/A' : (1000 * t).toFixed(1) + ' ms';
}
if (index >= fixture.length) {
setText('total-size', kb(totalSize));
setText('esprima-time', (1000 * totalTime.esprima).toFixed(1) + ' ms');
setText('parsejs-time', (1000 * totalTime.parsejs).toFixed(1) + ' ms');
setText('zeparser-time', (1000 * totalTime.zeparser).toFixed(1) + ' ms');
if (totalTime.narcissus > 0) {
setText('narcissus-time', (1000 * totalTime.narcissus).toFixed(1) + ' ms');
}
setText('esprima-time', formatTime(totalTime.esprima));
setText('parsejs-time', formatTime(totalTime.parsejs));
setText('zeparser-time', formatTime(totalTime.zeparser));
setText('narcissus-time', formatTime(totalTime.narcissus));
ready();
return;
}
@ -208,7 +210,7 @@ function runBenchmarks() {
benchmark = new window.Benchmark(test, fn, {
'onComplete': function () {
setText(parser + '-' + this.name, (1000 * this.stats.mean).toFixed(1) + ' ms');
setText(parser + '-' + this.name, formatTime(this.stats.mean));
totalSize += source.length;
totalTime[parser] += this.stats.mean;
}
@ -247,6 +249,16 @@ function runBenchmarks() {
}
}
if (typeof window.Narcissus !== 'object') {
window.Narcissus = {
parser: {
parse: function (code) {
throw new Error('Narcissus is not available!');
}
}
};
}
runBenchmark();
};

3
node_modules/esprima/test/coverage.footer.html generated vendored Normal file
View File

@ -0,0 +1,3 @@
</div>
</body>
</html>

37
node_modules/esprima/test/coverage.header.html generated vendored Normal file
View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Esprima: Coverage Analysis Report</title>
<link rel="stylesheet" type="text/css" href="../assets/style.css"/>
</head>
<style>
span.covered {
}
span.uncovered {
background: #FDD;
}
span.partial {
background: #FFA;
}
</style>
<body>
<div class="container">
<div class="topbar">
<ul class="nav">
<li><a href="../index.html">&larr; Home</a></li>
<li><a href="http://github.com/ariya/esprima">Code</a></li>
<li><a href="http://wiki.esprima.org">Documentation</a></li>
<li><a href="http://issues.esprima.org">Issues</a></li>
</ul>
</div>
<h1>Coverage Analysis <small>ensures systematic exercise of the parser</small></h1>
<p><strong>Note</strong>: This is not a live (in-browser) code coverage report.
The analysis is <a href="http://code.google.com/p/esprima/wiki/Testing#Code_coverage_test">performed</a> offline
(using <a href="https://github.com/itay/node-cover">node-cover</a>).<br>

3617
node_modules/esprima/test/coverage.html generated vendored Normal file

File diff suppressed because one or more lines are too long

9653
node_modules/esprima/test/test.js generated vendored

File diff suppressed because it is too large Load Diff

164
node_modules/esprima/tools/generate-unicode-regex.py generated vendored Normal file
View File

@ -0,0 +1,164 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# By Yusuke Suzuki <utatane.tea@gmail.com>
# Modified by Mathias Bynens <http://mathiasbynens.be/>
# http://code.google.com/p/esprima/issues/detail?id=110
import sys
import string
import re
class RegExpGenerator(object):
def __init__(self, detector):
self.detector = detector
def generate_identifier_start(self):
r = [ ch for ch in range(0xFFFF + 1) if self.detector.is_identifier_start(ch)]
return self._generate_range(r)
def generate_identifier_part(self):
r = [ ch for ch in range(0xFFFF + 1) if self.detector.is_identifier_part(ch)]
return self._generate_range(r)
def generate_non_ascii_identifier_start(self):
r = [ ch for ch in xrange(0x0080, 0xFFFF + 1) if self.detector.is_identifier_start(ch)]
return self._generate_range(r)
def generate_non_ascii_identifier_part(self):
r = [ ch for ch in range(0x0080, 0xFFFF + 1) if self.detector.is_identifier_part(ch)]
return self._generate_range(r)
def generate_non_ascii_separator_space(self):
r = [ ch for ch in range(0x0080, 0xFFFF + 1) if self.detector.is_separator_space(ch)]
return self._generate_range(r)
def _generate_range(self, r):
if len(r) == 0:
return '[]'
buf = []
start = r[0]
end = r[0]
predict = start + 1
r = r[1:]
for code in r:
if predict == code:
end = code
predict = code + 1
continue
else:
if start == end:
buf.append("\\u%04X" % start)
elif end == start + 1:
buf.append("\\u%04X\\u%04X" % (start, end))
else:
buf.append("\\u%04X-\\u%04X" % (start, end))
start = code
end = code
predict = code + 1
if start == end:
buf.append("\\u%04X" % start)
else:
buf.append("\\u%04X-\\u%04X" % (start, end))
return '[' + ''.join(buf) + ']'
class Detector(object):
def __init__(self, data):
self.data = data
def is_ascii(self, ch):
return ch < 0x80
def is_ascii_alpha(self, ch):
v = ch | 0x20
return v >= ord('a') and v <= ord('z')
def is_decimal_digit(self, ch):
return ch >= ord('0') and ch <= ord('9')
def is_octal_digit(self, ch):
return ch >= ord('0') and ch <= ord('7')
def is_hex_digit(self, ch):
v = ch | 0x20
return self.is_decimal_digit(c) or (v >= ord('a') and v <= ord('f'))
def is_digit(self, ch):
return self.is_decimal_digit(ch) or self.data[ch] == 'Nd'
def is_ascii_alphanumeric(self, ch):
return self.is_decimal_digit(ch) or self.is_ascii_alpha(ch)
def _is_non_ascii_identifier_start(self, ch):
c = self.data[ch]
return c == 'Lu' or c == 'Ll' or c == 'Lt' or c == 'Lm' or c == 'Lo' or c == 'Nl'
def _is_non_ascii_identifier_part(self, ch):
c = self.data[ch]
return c == 'Lu' or c == 'Ll' or c == 'Lt' or c == 'Lm' or c == 'Lo' or c == 'Nl' or c == 'Mn' or c == 'Mc' or c == 'Nd' or c == 'Pc' or ch == 0x200C or ch == 0x200D
def is_separator_space(self, ch):
return self.data[ch] == 'Zs'
def is_white_space(self, ch):
return ch == ord(' ') or ch == ord("\t") or ch == 0xB or ch == 0xC or ch == 0x00A0 or ch == 0xFEFF or self.is_separator_space(ch)
def is_line_terminator(self, ch):
return ch == 0x000D or ch == 0x000A or self.is_line_or_paragraph_terminator(ch)
def is_line_or_paragraph_terminator(self, ch):
return ch == 0x2028 or ch == 0x2029
def is_identifier_start(self, ch):
if self.is_ascii(ch):
return ch == ord('$') or ch == ord('_') or ch == ord('\\') or self.is_ascii_alpha(ch)
return self._is_non_ascii_identifier_start(ch)
def is_identifier_part(self, ch):
if self.is_ascii(ch):
return ch == ord('$') or ch == ord('_') or ch == ord('\\') or self.is_ascii_alphanumeric(ch)
return self._is_non_ascii_identifier_part(ch)
def analyze(source):
data = []
dictionary = {}
with open(source) as uni:
flag = False
first = 0
for line in uni:
d = string.split(line.strip(), ";")
val = int(d[0], 16)
if flag:
if re.compile("<.+, Last>").match(d[1]):
# print "%s : u%X" % (d[1], val)
flag = False
for t in range(first, val+1):
dictionary[t] = str(d[2])
else:
raise "Database Exception"
else:
if re.compile("<.+, First>").match(d[1]):
# print "%s : u%X" % (d[1], val)
flag = True
first = val
else:
dictionary[val] = str(d[2])
for i in range(0xFFFF + 1):
if dictionary.get(i) == None:
data.append("Un")
else:
data.append(dictionary[i])
return RegExpGenerator(Detector(data))
def main(source):
generator = analyze(source)
print generator.generate_non_ascii_identifier_start()
print generator.generate_non_ascii_identifier_part()
print generator.generate_non_ascii_separator_space()
if __name__ == '__main__':
main(sys.argv[1])

28
node_modules/esprima/tools/update-coverage.sh generated vendored Executable file
View File

@ -0,0 +1,28 @@
#!/bin/bash
if [ `command -v cover` ]; then
REVISION=`git log -1 --pretty=%h`
DATE=`git log -1 --pretty=%cD | cut -c 6-16`
echo "Running coverage analysis..."
rm -rf .coverage_data
rm -rf cover_index
cover run test/test.js
cover report html
cat test/coverage.header.html > test/coverage.html
echo "Tested revision: <a href='https://github.com/ariya/esprima/commit/${REVISION}'>${REVISION}</a>" >> test/coverage.html
echo " (dated ${DATE}).</p>" >> test/coverage.html
echo '<pre>' >> test/coverage.html
grep -h '^<span class' cover_html/*esprima\.js\.html >> test/coverage.html
echo '</pre>' >> test/coverage.html
cat test/coverage.footer.html >> test/coverage.html
rm -rf cover_html
rm -rf .coverage_data
else
echo "Please install node-cover first!"
fi