commit 8967ddc77d00ad6558e47540238e96bdcdf0d310 Author: benedikt willi Date: Tue Apr 15 11:04:48 2014 +0200 Initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..1db9728 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +#AnnotateJS + +This project intends to automatically create JSDoc annotations based on Javascript sourcecode \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..3ac1052 --- /dev/null +++ b/index.html @@ -0,0 +1,15 @@ + + + + + + + + + + + +
Let's use some esprima!
+
Let's use some esprima!
+ + \ No newline at end of file diff --git a/scripts/annotate.js b/scripts/annotate.js new file mode 100644 index 0000000..b599eca --- /dev/null +++ b/scripts/annotate.js @@ -0,0 +1,209 @@ +/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ +/*global define */ + +define(['exports', 'underscore', 'lib/esprima-master/esprima'], function (exports, _, esprima) { + + /** + * From esmorph.js + * @param {type} object to run visitor on + * @param {type} visitor Description + * @param {type} path Description + */ + function traverse(object, visitor, path) { + var key, child; + + if (typeof path === 'undefined') { + path = []; + } + + visitor.call(null, object, path); + for (key in object) { + if (object.hasOwnProperty(key)) { + child = object[key]; + if (typeof child === 'object' && child !== null) { + traverse(child, visitor, [object].concat(path)); + } + } + } + } + + /** + * From esmorph.js + * Find a return statement within a function which is the exit for + * the said function. If there is no such explicit exit, a null + * will be returned instead. + * @param {object} functionNode The node that should be inspected for a return statement + */ + function findExit(functionNode) { + var exit = null; + + function isFunction(node) { + return node.type && node.range && + (node.type === esprima.Syntax.FunctionDeclaration || + node.type === esprima.Syntax.FunctionExpression); + } + + traverse(functionNode, function (node, path) { + var i, parent; + if (node.type === esprima.Syntax.ReturnStatement) { + for (i = 0; i < path.length; ++i) { + parent = path[i]; + if (isFunction(parent)) { + if (parent.range === functionNode.range) { + exit = node; + } + break; + } + } + } + }); + + return exit; + } + + /** + * Add node.loc.start.column spaces to get the same indentation as the node + * @param {type} node The node you want to get the indentation for + */ + function getIndentation(node) { + return Array(node.loc.start.column).join(' '); + } + + function buildJsDoc(node, indentation) { + var jsDoc = ""; + switch (node.type) { + case esprima.Syntax.Literal: + jsDoc += "\n" + indentation + " * @type {" + typeof node.value + "}"; + break; + case esprima.Syntax.FunctionExpression: + jsDoc += "\n" + indentation + " * @type {function}"; + _.forEach(node.params, function (v, key) { + jsDoc += getParamString(v, indentation); + }); + jsDoc += getReturnString(node, indentation); + break; + case esprima.Syntax.ObjectExpression: + jsDoc += "\n" + indentation + " * @type {object}"; + break; + default: + break; + } + return jsDoc; + } + + /** + * Returns the jsDoc string representation for a parameter of a function + * @param {type} param The parameter you want to get the jsDoc representation for + */ + function getParamString(param, indentation) { + return "\n" + indentation + " * @param {Type} Description"; + } + + /** + * Try to find a return statement to a function, if it finds one, return the corresponding jsDoc string + * @param {type} node The node from which you want to find the return value. + */ + function getReturnString(node, indentation) { + var returnStatement = findExit(node); + //Todo: find the tpye of the returned argument, as it is, it's always an object + return (_.isObject(returnStatement) ? "\n" + indentation + " * @return {" + typeof returnStatement.argument + "} Description" : ""); + } + + /** + * Annotate ExpressionStatement + * @param {type} node Description + * @param {type} parent Description + */ + exports.ExpressionStatement = function (node, parent) { + var indentation = getIndentation(node); + var jsDoc = "\n" + indentation + "/**"; + + switch (node.expression.type) { + case esprima.Syntax.Literal: + case esprima.Syntax.CallExpression: + return; + case esprima.Syntax.AssignmentExpression: + if (node.expression.left.property.name === node.expression.left.property.name.toUpperCase()) jsDoc += "\n" + indentation + " * @const"; + jsDoc += buildJsDoc(node.expression.right, indentation); + } + + jsDoc += "\n" + indentation + " **/\n" + indentation; + return jsDoc; + }; + + /** + * Annotate VariableDeclaration + * @param {type} node Description + * @param {type} parent Description + * @returns {type} Description + */ + exports.VariableDeclaration = function (node, parent) { + // Add node.loc.start.column spaces to get the same indentation as the node + var indentation = getIndentation(node); + var jsDoc = "\n" + indentation + "/**"; + + // Add each declaration + _.forEach(node.declarations, function (value, key) { + jsDoc += "\n" + indentation + " * @name " + value.id.name; //Todo: remove this line, as jsDoc will check the name at generation time + + // check if variable is uppercase, if so, it's a constant + if (value.id.name === value.id.name.toUpperCase()) jsDoc += "\n" + indentation + " * @const"; + + // check the type with which the variable is initialized + if (value.init !== null) { + jsDoc += buildJsDoc(value.init, indentation); + } + + // check if first character is an underline, if so it's a private variable + if (value.id.name.charAt(0) === '_') jsDoc += "\n" + indentation + " * @private"; + }); + jsDoc += "\n" + indentation + " **/\n" + indentation; + return jsDoc; + }; + + /** + * Annotate FunctionDeclaration + * @param {type} node Description + * @param {type} parent Description + */ + exports.FunctionDeclaration = function (node, parent) { + var indentation = getIndentation(node); + var jsDoc = "\n" + indentation + "/**"; + jsDoc += "\n" + indentation + " * @name " + node.id.name; + + // Add each parameter + _.forEach(node.params, function (value, key) { + jsDoc += getParamString(value, indentation); + }); + jsDoc += getReturnString(node, indentation); + jsDoc += "\n" + indentation + " **/\n" + indentation; + + return jsDoc; + }; + + /** + * Annotate Properties + * @param {type} node Description + * @param {type} parent Description + */ + exports.Property = function (node, parent) { + var indentation = getIndentation(node); + var jsDoc = "\n" + indentation + "/**"; + jsDoc += "\n" + indentation + " * @name " + node.key.name; + + // check if variable is uppercase, if so, it's a constant + if (node.key.name === node.key.name.toUpperCase()) jsDoc += "\n" + indentation + " * @const"; + + // check the type with which the variable is initialized + if (node.value !== null) { + jsDoc += buildJsDoc(node.value, indentation); + } + + // check if first character is an underline, if so it's a private variable + if (node.key.name.charAt(0) === '_') jsDoc += "\n" + indentation + " * @private"; + + jsDoc += "\n" + indentation + " **/\n" + indentation; + + return jsDoc; + }; +}); \ No newline at end of file diff --git a/scripts/lib/esprima-master/.eslintrc b/scripts/lib/esprima-master/.eslintrc new file mode 100755 index 0000000..73dbc47 --- /dev/null +++ b/scripts/lib/esprima-master/.eslintrc @@ -0,0 +1,92 @@ +{ + "env": { + "browser": true, + "node": true, + "amd": true + }, + + "rules": { + "no-alert": 2, + "no-array-constructor": 2, + "no-caller": 2, + "no-bitwise": 0, + "no-catch-shadow": 2, + "no-console": 2, + "no-comma-dangle": 2, + "no-control-regex": 2, + "no-debugger": 2, + "no-div-regex": 2, + "no-dupe-keys": 2, + "no-else-return": 2, + "no-empty": 2, + "no-empty-class": 2, + "no-eq-null": 2, + "no-eval": 2, + "no-ex-assign": 2, + "no-func-assign": 2, + "no-floating-decimal": 2, + "no-implied-eval": 2, + "no-with": 2, + "no-fallthrough": 2, + "no-global-strict": 2, + "no-unreachable": 2, + "no-undef": 2, + "no-undef-init": 2, + "no-unused-expressions": 0, + "no-octal": 2, + "no-octal-escape": 2, + "no-obj-calls": 2, + "no-multi-str": 2, + "no-new-wrappers": 2, + "no-new": 2, + "no-new-func": 2, + "no-native-reassign": 2, + "no-plusplus": 0, + "no-delete-var": 2, + "no-return-assign": 2, + "no-new-object": 2, + "no-label-var": 2, + "no-ternary": 0, + "no-self-compare": 2, + "no-sync": 2, + "no-underscore-dangle": 2, + "no-loop-func": 2, + "no-empty-label": 2, + "no-unused-vars": 0, + "no-script-url": 2, + "no-proto": 2, + "no-iterator": 2, + "no-mixed-requires": [0, false], + "no-wrap-func": 2, + "no-shadow": 2, + "no-use-before-define": 0, + "no-redeclare": 2, + "no-regex-spaces": 2, + + "brace-style": 0, + "block-scoped-var": 0, + "camelcase": 2, + "complexity": [0, 11], + "consistent-this": [0, "that"], + "curly": 2, + "dot-notation": 2, + "eqeqeq": 2, + "guard-for-in": 0, + "max-depth": [0, 4], + "max-len": [0, 80, 4], + "max-params": [0, 3], + "max-statements": [0, 10], + "new-cap": 2, + "new-parens": 2, + "one-var": 0, + "quotes": [2, "single"], + "quote-props": 0, + "radix": 0, + "semi": 2, + "strict": 2, + "unnecessary-strict": 0, + "use-isnan": 2, + "wrap-iife": 2, + "wrap-regex": 0 + } +} diff --git a/scripts/lib/esprima-master/.gitignore b/scripts/lib/esprima-master/.gitignore new file mode 100755 index 0000000..62562b7 --- /dev/null +++ b/scripts/lib/esprima-master/.gitignore @@ -0,0 +1,2 @@ +coverage +node_modules diff --git a/scripts/lib/esprima-master/.jscs.json b/scripts/lib/esprima-master/.jscs.json new file mode 100755 index 0000000..6094a95 --- /dev/null +++ b/scripts/lib/esprima-master/.jscs.json @@ -0,0 +1,119 @@ +{ + "requireCurlyBraces": [ + "if", + "else", + "for", + "while", + "do", + "try", + "catch" + ], + "requireSpaceAfterKeywords": [ + "if", + "else", + "for", + "while", + "do", + "switch", + "return", + "try", + "catch" + ], + "requireParenthesesAroundIIFE": true, + "requireSpacesInFunctionExpression": { + "beforeOpeningCurlyBrace": true + }, + "requireMultipleVarDecl": true, + "disallowEmptyBlocks": true, + "disallowSpacesInsideObjectBrackets": true, + "disallowSpacesInsideParentheses": true, + "requireSpacesInsideObjectBrackets": "all", + "disallowDanglingUnderscores": true, + "disallowSpaceAfterObjectKeys": true, + "requireCommaBeforeLineBreak": true, + "requireOperatorBeforeLineBreak": [ + "?", + "+", + "-", + "/", + "*", + "=", + "==", + "===", + "!=", + "!==", + ">", + ">=", + "<", + "<=" + ], + "disallowLeftStickedOperators": [ + "?", + "+", + "-", + "/", + "*", + "=", + "==", + "===", + "!=", + "!==", + ">", + ">=", + "<", + "<=" + ], + "requireRightStickedOperators": ["!"], + "disallowRightStickedOperators": [ + "?", + "+", + "/", + "*", + ":", + "=", + "==", + "===", + "!=", + "!==", + ">", + ">=", + "<", + "<=" + ], + "requireLeftStickedOperators": [","], + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforeBinaryOperators": [ + "+", + "-", + "/", + "*", + "=", + "==", + "===", + "!=", + "!==" + ], + "requireSpaceAfterBinaryOperators": [ + "+", + "-", + "/", + "*", + "=", + "==", + "===", + "!=", + "!==" + ], + "disallowImplicitTypeConversion": ["numeric", "boolean", "binary", "string"], + "requireCamelCaseOrUpperCaseIdentifiers": true, + "disallowKeywords": ["with"], + "disallowMultipleLineStrings": true, + "validateLineBreaks": "LF", + "validateQuoteMarks": "'", + "disallowMixedSpacesAndTabs": true, + "disallowTrailingWhitespace": true, + "disallowKeywordsOnNewLine": ["else"], + "requireLineFeedAtFileEnd": true, + "requireDotNotation": true +} diff --git a/scripts/lib/esprima-master/.npmignore b/scripts/lib/esprima-master/.npmignore new file mode 100755 index 0000000..88dc4e8 --- /dev/null +++ b/scripts/lib/esprima-master/.npmignore @@ -0,0 +1,8 @@ +.git +.travis.yml +/node_modules/ +/assets/ +/coverage/ +/demo/ +/test/3rdparty +/tools/ diff --git a/scripts/lib/esprima-master/.travis.yml b/scripts/lib/esprima-master/.travis.yml new file mode 100755 index 0000000..da1b80b --- /dev/null +++ b/scripts/lib/esprima-master/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.8 + - 0.9 + diff --git a/scripts/lib/esprima-master/CONTRIBUTING.md b/scripts/lib/esprima-master/CONTRIBUTING.md new file mode 100755 index 0000000..7ed87e5 --- /dev/null +++ b/scripts/lib/esprima-master/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# Contribution Guide + +This page describes how to contribute changes to Esprima. + +Please do **not** create a pull request without reading this guide first. Failure to do so may result in the **rejection** of the pull request. + +**1. Create a ticket in the [issue tracker](http://issues.esprima.org)**. +This serves as a placeholder for important feedback, review, or any future updates. + +**2. Run all the tests**. This requires Node.js: `npm install` to set up, `npm test` to run the tests. + +**3. Work on a feature branch**. If the change still needs some tweaks, it will not clutter the master branch. + +**4. Write a reasonable commit message:** + +* Keep the first line < 72 characters. Write additional paragraphs if necessary. +* Put the link to the ticket. This is important for cross-referencing purposes. + + +For more information, please check the [detailed contribution guide](http://esprima.org/doc/index.html#contribution). diff --git a/scripts/lib/esprima-master/ChangeLog b/scripts/lib/esprima-master/ChangeLog new file mode 100755 index 0000000..5ecfb4a --- /dev/null +++ b/scripts/lib/esprima-master/ChangeLog @@ -0,0 +1,49 @@ +2014-03-26: Version 1.1.1 + + * Fix token handling of forward slash after an array literal (issue 512) + +2014-03-23: Version 1.1.0 + + * Optionally attach comments to the owning syntax nodes (issue 197) + * Simplify binary parsing with stack-based shift reduce (issue 352) + * Always include the raw source of literals (issue 376) + * Add optional input source information (issue 386) + * Tokenizer API for pure lexical scanning (issue 398) + * Improve the web site and its online demos (issue 337, 400, 404) + * Performance improvement for location tracking (issue 417, 424) + * Support HTML comment syntax (issue 451) + * Drop support for legacy browsers (issue 474) + +2013-08-27: Version 1.0.4 + + * Minimize the payload for packages (issue 362) + * Fix missing cases on an empty switch statement (issue 436) + * Support escaped ] in regexp literal character classes (issue 442) + * Tolerate invalid left-hand side expression (issue 130) + +2013-05-17: Version 1.0.3 + + * Variable declaration needs at least one declarator (issue 391) + * Fix benchmark's variance unit conversion (issue 397) + * IE < 9: \v should be treated as vertical tab (issue 405) + * Unary expressions should always have prefix: true (issue 418) + * Catch clause should only accept an identifier (issue 423) + * Tolerate setters without parameter (issue 426) + +2012-11-02: Version 1.0.2 + + Improvement: + + * Fix esvalidate JUnit output upon a syntax error (issue 374) + +2012-10-28: Version 1.0.1 + + Improvements: + + * esvalidate understands shebang in a Unix shell script (issue 361) + * esvalidate treats fatal parsing failure as an error (issue 361) + * Reduce Node.js package via .npmignore (issue 362) + +2012-10-22: Version 1.0.0 + + Initial release. diff --git a/scripts/lib/esprima-master/LICENSE.BSD b/scripts/lib/esprima-master/LICENSE.BSD new file mode 100755 index 0000000..3e580c3 --- /dev/null +++ b/scripts/lib/esprima-master/LICENSE.BSD @@ -0,0 +1,19 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL 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. diff --git a/scripts/lib/esprima-master/README.md b/scripts/lib/esprima-master/README.md new file mode 100755 index 0000000..588acaf --- /dev/null +++ b/scripts/lib/esprima-master/README.md @@ -0,0 +1,24 @@ +**Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, +standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +parser written in ECMAScript (also popularly known as +[JavaScript](http://en.wikipedia.org/wiki/JavaScript>JavaScript)). +Esprima is created and maintained by [Ariya Hidayat](http://twitter.com/ariyahidayat), +with the help of [many contributors](https://github.com/ariya/esprima/contributors). + +### Features + +- Full support for ECMAScript 5.1 ([ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) +- Sensible [syntax tree format](http://esprima.org/doc/index.html#ast) compatible with Mozilla +[Parser AST](https://developer.mozilla.org/en/SpiderMonkey/Parser_API) +- Optional tracking of syntax node location (index-based and line-column) +- Heavily tested (> 700 [unit tests](http://esprima.org/test/) with [full code coverage](http://esprima.org/test/coverage.html)) +- [Partial support](http://esprima.org/doc/es6.html) support for ECMAScript 6 + +Esprima serves as a **building block** for some JavaScript +language tools, from [code instrumentation](http://esprima.org/demo/functiontrace.html) +to [editor autocompletion](http://esprima.org/demo/autocomplete.html). + +Esprima runs on many popular web browsers, as well as other ECMAScript platforms such as +[Rhino](http://www.mozilla.org/rhino), [Nashorn](http://openjdk.java.net/projects/nashorn/), and [Node.js](https://npmjs.org/package/esprima). + +For more information, check the web site [esprima.org](http://esprima.org). diff --git a/scripts/lib/esprima-master/assets/foundation/foundation.min.css b/scripts/lib/esprima-master/assets/foundation/foundation.min.css new file mode 100755 index 0000000..5744060 --- /dev/null +++ b/scripts/lib/esprima-master/assets/foundation/foundation.min.css @@ -0,0 +1 @@ +*,*:before,*:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%}body{background:#fff;font-family:"Helvetica Neue","Helvetica",Helvetica,Arial,sans-serif;font-weight:normal;font-style:normal;font-size:14px;line-height:1;color:#222;position:relative;-webkit-font-smoothing:antialiased}a img{border:none}a{color:#2ba6cb;text-decoration:none;line-height:inherit}a:hover{color:#2795b6}a:focus{color:#2795b6}p a,p a:visited{line-height:inherit}.left{float:left}.right{float:right}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.hide{display:none}.hide-override{display:none !important}.highlight{background:#ff9}#googlemap img,object,embed{max-width:none}#map_canvas embed{max-width:none}#map_canvas img{max-width:none}#map_canvas object{max-width:none}figure{margin:0}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;font-size:14px;direction:ltr}p{font-family:inherit;font-weight:normal;font-size:14px;line-height:1.6;margin-bottom:17px}p.lead{font-size:17.5px;line-height:1.6;margin-bottom:17px}aside p{font-size:13px;line-height:1.35;font-style:italic}h1,h2,h3,h4,h5,h6{font-family:"Helvetica Neue","Helvetica",Helvetica,Arial,sans-serif;font-weight:bold;font-style:normal;color:#222;text-rendering:optimizeLegibility;line-height:1.1;margin-bottom:14px;margin-top:14px}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-size:60%;color:#6f6f6f;line-height:0}h1{font-size:44px}h2{font-size:37px}h3{font-size:27px}h4{font-size:23px}h5{font-size:17px}h6{font-size:14px}hr{border:solid #ddd;border-width:1px 0 0;clear:both;margin:22px 0 21px;height:0}.subheader{line-height:1.3;color:#6f6f6f;font-weight:300;margin-bottom:17px}em,i{font-style:italic;line-height:inherit}strong,b{font-weight:bold;line-height:inherit}small{font-size:60%;line-height:inherit}code{font-weight:bold;background:#ff9}ul,ol,dl{font-size:14px;line-height:1.6;margin-bottom:17px;list-style-position:outside}ul li ul,ul li ol{margin-left:20px;margin-bottom:0}ul.square,ul.circle,ul.disc{margin-left:17px}ul.square{list-style-type:square}ul.square li ul{list-style:inherit}ul.circle{list-style-type:circle}ul.circle li ul{list-style:inherit}ul.disc{list-style-type:disc}ul.disc li ul{list-style:inherit}ul.no-bullet{list-style:none}ul.large li{line-height:21px}ol{margin-left:20px}ol li ul,ol li ol{margin-left:20px;margin-bottom:0}blockquote,blockquote p{line-height:1.5;color:#6f6f6f}blockquote{margin:0 0 17px;padding:9px 20px 0 19px;border-left:1px solid #ddd}blockquote cite{display:block;font-size:13px;color:#555}blockquote cite:before{content:"\2014 \0020"}blockquote cite a,blockquote cite a:visited{color:#555}abbr,acronym{text-transform:uppercase;font-size:90%;color:#222;border-bottom:1px solid #ddd;cursor:help}abbr{text-transform:none}.print-only{display:none !important}@media print{*{background:transparent !important;color:black !important;box-shadow:none !important;text-shadow:none !important;filter:none !important;-ms-filter:none !important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.hide-on-print{display:none !important}.print-only{display:block !important}.hide-for-print{display:none !important}.show-for-print{display:inherit !important}}form{margin:0 0 19.41641px}.row form .row{margin:0 -6px}.row form .row .column,.row form .row .columns{padding:0 6px}.row form .row.collapse{margin:0}.row form .row.collapse .column,.row form .row.collapse .columns{padding:0}label{font-size:14px;color:#4d4d4d;cursor:pointer;display:block;font-weight:500;margin-bottom:3px}label.right{float:none;text-align:right}label.inline{line-height:32px;margin:0 0 12px 0}.prefix,.postfix{display:block;position:relative;z-index:2;text-align:center;width:100%;padding-top:0;padding-bottom:0;height:32px;line-height:31px}a.button.prefix,a.button.postfix{padding-left:0;padding-right:0;text-align:center}span.prefix,span.postfix{background:#f2f2f2;border:1px solid #ccc}.prefix{left:2px;-moz-border-radius-topleft:2px;-webkit-border-top-left-radius:2px;border-top-left-radius:2px;-moz-border-radius-bottomleft:2px;-webkit-border-bottom-left-radius:2px;border-bottom-left-radius:2px;overflow:hidden}.postfix{right:2px;-moz-border-radius-topright:2px;-webkit-border-top-right-radius:2px;border-top-right-radius:2px;-moz-border-radius-bottomright:2px;-webkit-border-bottom-right-radius:2px;border-bottom-right-radius:2px}input[type="text"],input[type="password"],input[type="date"],input[type="datetime"],input[type="email"],input[type="number"],input[type="search"],input[type="tel"],input[type="time"],input[type="url"],textarea{background-color:#fff;font-family:inherit;border:1px solid #ccc;-webkit-border-radius:2px;-moz-border-radius:2px;-ms-border-radius:2px;-o-border-radius:2px;border-radius:2px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);color:rgba(0,0,0,0.75);display:block;font-size:14px;margin:0 0 12px 0;padding:6px;height:32px;width:100%;-webkit-transition:all 0.15s linear;-moz-transition:all 0.15s linear;-o-transition:all 0.15s linear;transition:all 0.15s linear}input[type="text"].oversize,input[type="password"].oversize,input[type="date"].oversize,input[type="datetime"].oversize,input[type="email"].oversize,input[type="number"].oversize,input[type="search"].oversize,input[type="tel"].oversize,input[type="time"].oversize,input[type="url"].oversize,textarea.oversize{font-size:17px;padding:4px 6px}input[type="text"]:focus,input[type="password"]:focus,input[type="date"]:focus,input[type="datetime"]:focus,input[type="email"]:focus,input[type="number"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="time"]:focus,input[type="url"]:focus,textarea:focus{background:#fafafa;border-color:#b3b3b3}input[type="text"][disabled],input[type="password"][disabled],input[type="date"][disabled],input[type="datetime"][disabled],input[type="email"][disabled],input[type="number"][disabled],input[type="search"][disabled],input[type="tel"][disabled],input[type="time"][disabled],input[type="url"][disabled],textarea[disabled]{background-color:#ddd}textarea{height:auto}select{width:100%}fieldset{border:solid 1px #ddd;-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:3px;padding:12px;margin:18px 0}fieldset legend{font-weight:bold;background:#fff;padding:0 3px;margin:0;margin-left:-3px}.error input,input.error,.error textarea,textarea.error,.error input:focus,input.error:focus,.error textarea:focus,textarea.error:focus{border-color:#c60f13;background-color:rgba(198,15,19,0.1)}.error input:focus,input.error:focus,.error textarea:focus,textarea.error:focus{outline-color:#f5797c}.error label,label.error{color:#c60f13}.error small,small.error{display:block;padding:6px 4px;margin-top:-13px;margin-bottom:12px;background:#c60f13;color:#fff;font-size:12px;font-weight:bold;-moz-border-radius-bottomleft:2px;-webkit-border-bottom-left-radius:2px;border-bottom-left-radius:2px;-moz-border-radius-bottomright:2px;-webkit-border-bottom-right-radius:2px;border-bottom-right-radius:2px}form.custom span.custom{display:inline-block;width:16px;height:16px;position:relative;top:2px;border:solid 1px #ccc;background:#fff}form.custom span.custom.radio{-webkit-border-radius:100px;-moz-border-radius:100px;-ms-border-radius:100px;-o-border-radius:100px;border-radius:100px}form.custom span.custom.checkbox:before{content:"";display:block;line-height:0.8;height:14px;width:14px;text-align:center;position:absolute;top:0;left:0;font-size:14px;color:#fff}form.custom span.custom.radio.checked:before{content:"";display:block;width:8px;height:8px;-webkit-border-radius:100px;-moz-border-radius:100px;-ms-border-radius:100px;-o-border-radius:100px;border-radius:100px;background:#222;position:relative;top:3px;left:3px}form.custom span.custom.checkbox.checked:before{content:"\00d7";color:#222}form.custom div.custom.dropdown{display:block;position:relative;width:auto;height:28px;margin-bottom:9px;margin-top:2px}form.custom div.custom.dropdown ul{overflow-y:auto;max-height:200px}form.custom div.custom.dropdown a.current{display:block;width:auto;line-height:26px;min-height:28px;padding:0;padding-left:6px;padding-right:38px;border:solid 1px #ddd;color:#141414;background-color:#fff;white-space:nowrap}form.custom div.custom.dropdown a.selector{position:absolute;width:27px;height:28px;display:block;right:0;top:0;border:solid 1px #ddd}form.custom div.custom.dropdown a.selector:after{content:"";display:block;content:"";display:block;width:0;height:0;border:solid 5px;border-color:#aaa transparent transparent transparent;position:absolute;left:50%;top:50%;margin-top:-2px;margin-left:-5px}form.custom div.custom.dropdown:hover a.selector:after,form.custom div.custom.dropdown.open a.selector:after{content:"";display:block;width:0;height:0;border:solid 5px;border-color:#222 transparent transparent transparent}form.custom div.custom.dropdown.open ul{display:block;z-index:10}form.custom div.custom.dropdown.small{width:134px !important}form.custom div.custom.dropdown.medium{width:254px !important}form.custom div.custom.dropdown.large{width:434px !important}form.custom div.custom.dropdown.expand{width:100% !important}form.custom div.custom.dropdown.open.small ul{width:134px !important}form.custom div.custom.dropdown.open.medium ul{width:254px !important}form.custom div.custom.dropdown.open.large ul{width:434px !important}form.custom div.custom.dropdown.open.expand ul{width:100% !important}form.custom div.custom.dropdown ul{position:absolute;width:auto;display:none;margin:0;left:0;top:27px;margin:0;padding:0;background:#fff;background:rgba(255,255,255,0.95);border:solid 1px #ccc}form.custom div.custom.dropdown ul li{color:#555;font-size:13px;cursor:pointer;padding:3px;padding-left:6px;padding-right:38px;min-height:18px;line-height:18px;margin:0;white-space:nowrap;list-style:none}form.custom div.custom.dropdown ul li.selected{background:#cdebf5;color:#000}form.custom div.custom.dropdown ul li.selected:after{content:"\2013";position:absolute;right:10px}form.custom div.custom.dropdown ul li:hover{background-color:#cdebf5;color:#000}form.custom div.custom.dropdown ul li:hover:after{content:"\2013";position:absolute;right:10px;color:#a3dbec}form.custom div.custom.dropdown ul li.selected:hover{background:#cdebf5;cursor:default;color:#000}form.custom div.custom.dropdown ul li.selected:hover:after{color:#000}form.custom div.custom.dropdown ul.show{display:block}form.custom .custom.disabled{background-color:#ddd}@-moz-document url-prefix(){form.custom div.custom.dropdown a.selector{height:28px}}.lt-ie9 form.custom div.custom.dropdown a.selector{height:28px}.row{width:940px;max-width:100%;min-width:768px;margin:0 auto}.row .row{width:auto;max-width:none;min-width:0;margin:0 -15px}.row.collapse .column,.row.collapse .columns{padding:0}.row .row{width:auto;max-width:none;min-width:0;margin:0 -15px}.row .row.collapse{margin:0}.column,.columns{float:left;min-height:1px;padding:0 15px;position:relative}.column.centered,.columns.centered{float:none;margin:0 auto}[class*="column"]+[class*="column"]:last-child{float:right}[class*="column"]+[class*="column"].end{float:left}.one,.row .one{width:8.33333%}.two,.row .two{width:16.66667%}.three,.row .three{width:25%}.four,.row .four{width:33.33333%}.five,.row .five{width:41.66667%}.six,.row .six{width:50%}.seven,.row .seven{width:58.33333%}.eight,.row .eight{width:66.66667%}.nine,.row .nine{width:75%}.ten,.row .ten{width:83.33333%}.eleven,.row .eleven{width:91.66667%}.twelve,.row .twelve{width:100%}.row .offset-by-one{margin-left:8.33333%}.row .offset-by-two{margin-left:16.66667%}.row .offset-by-three{margin-left:25%}.row .offset-by-four{margin-left:33.33333%}.row .offset-by-five{margin-left:41.66667%}.row .offset-by-six{margin-left:50%}.row .offset-by-seven{margin-left:58.33333%}.row .offset-by-eight{margin-left:66.66667%}.row .offset-by-nine{margin-left:75%}.row .offset-by-ten{margin-left:83.33333%}.push-two{left:16.66667%}.pull-two{right:16.66667%}.push-three{left:25%}.pull-three{right:25%}.push-four{left:33.33333%}.pull-four{right:33.33333%}.push-five{left:41.66667%}.pull-five{right:41.66667%}.push-six{left:50%}.pull-six{right:50%}.push-seven{left:58.33333%}.pull-seven{right:58.33333%}.push-eight{left:66.66667%}.pull-eight{right:66.66667%}.push-nine{left:75%}.pull-nine{right:75%}.push-ten{left:83.33333%}.pull-ten{right:83.33333%}img{height:auto}img,object,embed{max-width:100%}img{-ms-interpolation-mode:bicubic}#map_canvas img,.map_canvas img{max-width:none!important}.row{*zoom:1}.row:before,.row:after{content:" ";display:table}.row:after{clear:both}.block-grid{display:block;overflow:hidden;padding:0}.block-grid>li{display:block;height:auto;float:left}.block-grid.one-up{margin:0}.block-grid.one-up>li{width:100%;padding:0 0 15px}.block-grid.two-up{margin:0 -15px}.block-grid.two-up>li{width:50%;padding:0 15px 15px}.block-grid.two-up>li:nth-child(2n+1){clear:both}.block-grid.three-up{margin:0 -12px}.block-grid.three-up>li{width:33.33333%;padding:0 12px 12px}.block-grid.three-up>li:nth-child(3n+1){clear:both}.block-grid.four-up{margin:0 -10px}.block-grid.four-up>li{width:25%;padding:0 10px 10px}.block-grid.four-up>li:nth-child(4n+1){clear:both}.block-grid.five-up{margin:0 -8px}.block-grid.five-up>li{width:20%;padding:0 8px 8px}.block-grid.five-up>li:nth-child(5n+1){clear:both}.block-grid.six-up{margin:0 -8px}.block-grid.six-up>li{width:16.66667%;padding:0 8px 8px}.block-grid.six-up>li:nth-child(6n+1){clear:both}.block-grid.seven-up{margin:0 -8px}.block-grid.seven-up>li{width:14.28571%;padding:0 8px 8px}.block-grid.seven-up>li:nth-child(7n+1){clear:both}.block-grid.eight-up{margin:0 -8px}.block-grid.eight-up>li{width:12.5%;padding:0 8px 8px}.block-grid.eight-up>li:nth-child(8n+1){clear:both}.block-grid.nine-up{margin:0 -8px}.block-grid.nine-up>li{width:11.11111%;padding:0 8px 8px}.block-grid.nine-up>li:nth-child(9n+1){clear:both}.block-grid.ten-up{margin:0 -8px}.block-grid.ten-up>li{width:10%;padding:0 8px 8px}.block-grid.ten-up>li:nth-child(10n+1){clear:both}.block-grid.eleven-up{margin:0 -8px}.block-grid.eleven-up>li{width:9.09091%;padding:0 8px 8px}.block-grid.eleven-up>li:nth-child(11n+1){clear:both}.block-grid.twelve-up{margin:0 -8px}.block-grid.twelve-up>li{width:8.33333%;padding:0 8px 8px}.block-grid.twelve-up>li:nth-child(12n+1){clear:both}.button{width:auto;background:#2ba6cb;border:1px solid #1e728c;-webkit-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;-moz-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;color:#fff;cursor:pointer;display:inline-block;font-family:inherit;font-size:14px;font-weight:bold;line-height:1;margin:0;padding:10px 20px 11px;position:relative;text-align:center;text-decoration:none;-webkit-transition:background-color 0.15s ease-in-out;-moz-transition:background-color 0.15s ease-in-out;-o-transition:background-color 0.15s ease-in-out;transition:background-color 0.15s ease-in-out}.button:hover,.button:focus{color:#fff;background-color:#2284a1}.button:active{-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.2) inset;-moz-box-shadow:0 1px 0 rgba(0,0,0,0.2) inset;box-shadow:0 1px 0 rgba(0,0,0,0.2) inset}.button.large{font-size:17px;padding:15px 30px 16px}.button.medium{font-size:14px}.button.small{font-size:11px;padding:7px 14px 8px}.button.tiny{font-size:10px;padding:5px 10px 6px}.button.expand{width:100%;text-align:center}.button.primary{background-color:#2ba6cb;border:1px solid #1e728c}.button.primary:hover,.button.primary:focus{background-color:#2284a1}.button.success{background-color:#5da423;border:1px solid #396516}.button.success:hover,.button.success:focus{background-color:#457a1a}.button.alert{background-color:#c60f13;border:1px solid #7f0a0c}.button.alert:hover,.button.alert:focus{background-color:#970b0e}.button.secondary{background-color:#e9e9e9;color:#1d1d1d;border:1px solid #c3c3c3}.button.secondary:hover,.button.secondary:focus{background-color:#d0d0d0}.button.radius{-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:3px}.button.round{-webkit-border-radius:1000px;-moz-border-radius:1000px;-ms-border-radius:1000px;-o-border-radius:1000px;border-radius:1000px}.button.full-width{width:100%;text-align:center;padding-left:0px !important;padding-right:0px !important}.button.left-align{text-align:left;text-indent:12px}.button.disabled,.button[disabled]{opacity:0.6;cursor:default;background:#2ba6cb;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.button.disabled:hover,.button[disabled]:hover{background:#2ba6cb}.button.disabled.success,.button[disabled].success{background-color:#5da423}.button.disabled.success:hover,.button.disabled.success:focus,.button[disabled].success:hover,.button[disabled].success:focus{background-color:#5da423;outline:none}.button.disabled.alert,.button[disabled].alert{background-color:#c60f13}.button.disabled.alert:hover,.button.disabled.alert:focus,.button[disabled].alert:hover,.button[disabled].alert:focus{background-color:#c60f13;outline:none}.button.disabled.secondary,.button[disabled].secondary{background-color:#e9e9e9}.button.disabled.secondary:hover,.button.disabled.secondary:focus,.button[disabled].secondary:hover,.button[disabled].secondary:focus{background-color:#e9e9e9;outline:none}input[type=submit].button,button.button{-webkit-appearance:none}@-moz-document url-prefix(){button::-moz-focus-inner,input[type="reset"]::-moz-focus-inner,input[type="button"]::-moz-focus-inner,input[type="submit"]::-moz-focus-inner,input[type="file"]>input[type="button"]::-moz-focus-inner{border:none;padding:0}input[type="submit"].tiny.button{padding:3px 10px 4px}input[type="submit"].small.button{padding:5px 14px 6px}input[type="submit"].button,input[type=submit].medium.button{padding:8px 20px 9px}input[type="submit"].large.button{padding:13px 30px 14px}}.button.dropdown{position:relative;padding-right:44px}.button.dropdown.large{padding-right:60px}.button.dropdown.small{padding-right:28px}.button.dropdown.tiny{padding-right:20px}.button.dropdown:after{content:"";display:block;width:0;height:0;border:solid 6px;border-color:#fff transparent transparent transparent;position:absolute;top:50%;right:20px;margin-top:-2px}.button.dropdown.large:after{content:"";display:block;width:0;height:0;border:solid 7px;border-color:#fff transparent transparent transparent;margin-top:-3px;right:30px}.button.dropdown.small:after{content:"";display:block;width:0;height:0;border:solid 5px;border-color:#fff transparent transparent transparent;margin-top:-2px;right:14px}.button.dropdown.tiny:after{content:"";display:block;width:0;height:0;border:solid 4px;border-color:#fff transparent transparent transparent;margin-top:-1px;right:10px}.button.dropdown>ul{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:none;position:absolute;left:-1px;background:#fff;background:rgba(255,255,255,0.95);list-style:none;margin:0;padding:0;border:1px solid #ccc;border-top:none;min-width:100%;z-index:40}.button.dropdown>ul li{width:100%;cursor:pointer;padding:0;min-height:18px;line-height:18px;margin:0;white-space:nowrap;list-style:none}.button.dropdown>ul li a,.button.dropdown>ul li button{display:block;color:#555;font-size:13px;font-weight:normal;padding:6px 14px;text-align:left}.button.dropdown>ul li button{width:100%;border:inherit;background:inherit;font-family:inherit;margin:inherit;-webkit-font-smoothing:antialiased}.button.dropdown>ul li:hover,.button.dropdown>ul li:focus{background-color:#e3f4f9;color:#222}.button.dropdown>ul li.divider{min-height:0;padding:0;height:1px;margin:4px 0;background:#ededed}.button.dropdown.up>ul{border-top:1px solid #ccc;border-bottom:none}.button.dropdown ul.no-hover.show-dropdown{display:block !important}.button.dropdown:hover>ul.no-hover{display:none}.button.dropdown.split{padding:0;position:relative}.button.dropdown.split:after{display:none}.button.dropdown.split:hover,.button.dropdown.split:focus{background-color:#2ba6cb}.button.dropdown.split.alert:hover,.button.dropdown.split.alert:focus{background-color:#c60f13}.button.dropdown.split.success:hover,.button.dropdown.split.success:focus{background-color:#5da423}.button.dropdown.split.secondary:hover,.button.dropdown.split.secondary:focus{background-color:#e9e9e9}.button.dropdown.split>a{color:#fff;display:block;padding:10px 50px 11px 20px;padding-left:20px;padding-right:50px;-webkit-transition:background-color 0.15s ease-in-out;-moz-transition:background-color 0.15s ease-in-out;-o-transition:background-color 0.15s ease-in-out;transition:background-color 0.15s ease-in-out}.button.dropdown.split>a:hover,.button.dropdown.split>a:focus{background-color:#2284a1;-webkit-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;-moz-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;box-shadow:0 1px 0 rgba(255,255,255,0.5) inset}.button.dropdown.split.large>a{padding:15px 75px 16px 30px;padding-left:30px;padding-right:75px}.button.dropdown.split.small>a{padding:7px 35px 8px 14px;padding-left:14px;padding-right:35px}.button.dropdown.split.tiny>a{padding:5px 25px 6px 10px;padding-left:10px;padding-right:25px}.button.dropdown.split>span{background-color:#2ba6cb;position:absolute;right:0;top:0;height:100%;width:30px;border-left:1px solid #1e728c;-webkit-box-shadow:1px 1px 0 rgba(255,255,255,0.5) inset;-moz-box-shadow:1px 1px 0 rgba(255,255,255,0.5) inset;box-shadow:1px 1px 0 rgba(255,255,255,0.5) inset;-webkit-transition:background-color 0.15s ease-in-out;-moz-transition:background-color 0.15s ease-in-out;-o-transition:background-color 0.15s ease-in-out;transition:background-color 0.15s ease-in-out}.button.dropdown.split>span:hover,.button.dropdown.split>span:focus{background-color:#2284a1}.button.dropdown.split>span:after{content:"";display:block;width:0;height:0;border:solid 6px;border-color:#fff transparent transparent transparent;position:absolute;top:50%;left:50%;margin-left:-6px;margin-top:-2px}.button.dropdown.split.secondary>span:after{content:"";display:block;width:0;height:0;border:solid 6px;border-color:#1d1d1d transparent transparent transparent}.button.dropdown.split.large span{width:45px}.button.dropdown.split.small span{width:21px}.button.dropdown.split.tiny span{width:15px}.button.dropdown.split.large span:after{content:"";display:block;width:0;height:0;border:solid 7px;border-color:#fff transparent transparent transparent;margin-top:-3px;margin-left:-7px}.button.dropdown.split.small span:after{content:"";display:block;width:0;height:0;border:solid 4px;border-color:#fff transparent transparent transparent;margin-top:-1px;margin-left:-4px}.button.dropdown.split.tiny span:after{content:"";display:block;width:0;height:0;border:solid 3px;border-color:#fff transparent transparent transparent;margin-top:-1px;margin-left:-3px}.button.dropdown.split.alert>span{background-color:#c60f13;border-left-color:#7f0a0c}.button.dropdown.split.success>span{background-color:#5da423;border-left-color:#396516}.button.dropdown.split.secondary>span{background-color:#e9e9e9;border-left-color:#c3c3c3}.button.dropdown.split.secondary>a{color:#1d1d1d}.button.dropdown.split.alert>a:hover,.button.dropdown.split.alert>span:hover,.button.dropdown.split.alert>a:focus,.button.dropdown.split.alert>span:focus{background-color:#970b0e}.button.dropdown.split.success>a:hover,.button.dropdown.split.success>span:hover,.button.dropdown.split.success>a:focus,.button.dropdown.split.success>span:focus{background-color:#457a1a}.button.dropdown.split.secondary>a:hover,.button.dropdown.split.secondary>span:hover,.button.dropdown.split.secondary>a:focus,.button.dropdown.split.secondary>span:focus{background-color:#d0d0d0}ul.button-group{list-style:none;padding:0;margin:0 0 12px;*zoom:1}ul.button-group:before,ul.button-group:after{content:" ";display:table}ul.button-group:after{clear:both}ul.button-group li{padding:0;margin:0 0 0 -1px;float:left}ul.button-group li:first-child{margin-left:0}ul.button-group.radius li .button,ul.button-group.radius li .button.radius,ul.button-group.radius li .button-rounded{-webkit-border-radius:0px;-moz-border-radius:0px;-ms-border-radius:0px;-o-border-radius:0px;border-radius:0px}ul.button-group.radius li:first-child .button,ul.button-group.radius li:first-child .button.radius{-moz-border-radius-topleft:3px;-webkit-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-bottomleft:3px;-webkit-border-bottom-left-radius:3px;border-bottom-left-radius:3px}ul.button-group.radius li:first-child .button.rounded{-moz-border-radius-topleft:1000px;-webkit-border-top-left-radius:1000px;border-top-left-radius:1000px;-moz-border-radius-bottomleft:1000px;-webkit-border-bottom-left-radius:1000px;border-bottom-left-radius:1000px}ul.button-group.radius li:last-child .button,ul.button-group.radius li:last-child .button.radius{-moz-border-radius-topright:3px;-webkit-border-top-right-radius:3px;border-top-right-radius:3px;-moz-border-radius-bottomright:3px;-webkit-border-bottom-right-radius:3px;border-bottom-right-radius:3px}ul.button-group.radius li:last-child .button.rounded{-moz-border-radius-topright:1000px;-webkit-border-top-right-radius:1000px;border-top-right-radius:1000px;-moz-border-radius-bottomright:1000px;-webkit-border-bottom-right-radius:1000px;border-bottom-right-radius:1000px}ul.button-group.even .button{width:100%}ul.button-group.even.two-up li{width:50%}ul.button-group.even.three-up li{width:33.3%}ul.button-group.even.three-up li:first-child{width:33.4%}ul.button-group.even.four-up li{width:25%}ul.button-group.even.five-up li{width:20%}div.button-bar{overflow:hidden}div.button-bar ul.button-group{float:left;margin-right:8px}div.button-bar ul.button-group:last-child{margin-left:0}.nav-bar{height:40px;background:#4d4d4d;margin-left:0;margin-top:20px;padding:0}.nav-bar>li{float:left;display:block;position:relative;padding:0;margin:0;border:1px solid #333;border-right:none;line-height:38px;-webkit-box-shadow:1px 0 0 rgba(255,255,255,0.2) inset;-moz-box-shadow:1px 0 0 rgba(255,255,255,0.2) inset;box-shadow:1px 0 0 rgba(255,255,255,0.2) inset}.nav-bar>li:first-child{-webkit-box-shadow:0 0 0;-moz-box-shadow:0 0 0;box-shadow:0 0 0}.nav-bar>li:last-child{border-right:solid 1px #333;-webkit-box-shadow:1px 0 0 rgba(255,255,255,0.2) inset,1px 0 0 rgba(255,255,255,0.2);-moz-box-shadow:1px 0 0 rgba(255,255,255,0.2) inset,1px 0 0 rgba(255,255,255,0.2);box-shadow:1px 0 0 rgba(255,255,255,0.2) inset,1px 0 0 rgba(255,255,255,0.2)}.nav-bar>li.active{background:#2ba6cb;border-color:#2284a1}.nav-bar>li.active>a{color:#fff;cursor:default}.nav-bar>li.active:hover{background:#2ba6cb;cursor:default}.nav-bar>li:hover{background:#333}.nav-bar>li>a{color:#e6e6e6}.nav-bar>li ul{margin-bottom:0}.nav-bar>li .flyout{display:none}.nav-bar>li.has-flyout>a:first-child{padding-right:40px;position:relative}.nav-bar>li.has-flyout>a:first-child:after{content:"";display:block;width:0;height:0;border:solid 4px;border-color:#e6e6e6 transparent transparent transparent;position:absolute;right:20px;top:17px}.nav-bar>li.has-flyout>a.flyout-toggle{border-left:0 !important;position:absolute;right:0;top:0;padding:20px;z-index:2;display:block}.nav-bar>li.has-flyout.is-touch>a:first-child{padding-right:55px}.nav-bar>li.has-flyout.is-touch>a.flyout-toggle{border-left:1px dashed #666}.nav-bar>li>a:first-child{position:relative;padding:0 20px;display:block;text-decoration:none;font-size:14px}.nav-bar>li>input{margin:0 10px}.nav-bar.vertical{height:auto;margin-top:0}.nav-bar.vertical>li{float:none;border-bottom:none;border-right:solid 1px #333;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.nav-bar.vertical>li.has-flyout>a:first-child:after{content:"";display:block;width:0;height:0;border:solid 4px;border-color:transparent transparent transparent #e6e6e6}.nav-bar.vertical>li .flyout{left:100%;top:-1px}.nav-bar.vertical>li .flyout.right{left:auto;right:100%}.nav-bar.vertical>li.active{border-right:solid 1px #2284a1}.nav-bar.vertical>li:last-child{border-bottom:solid 1px #333}.flyout{background:#f2f2f2;padding:20px;margin:0;border:1px solid #d9d9d9;position:absolute;top:39px;left:-1px;width:250px;z-index:40;-webkit-box-shadow:0 1px 5px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 5px rgba(0,0,0,0.1);box-shadow:0 1px 5px rgba(0,0,0,0.1)}.flyout p{line-height:1.2;font-size:13px}.flyout *:first-child{margin-top:0}.flyout *:last-child{margin-bottom:0}.flyout.small{width:166.66667px}.flyout.large{width:437.5px}.flyout.right{left:auto;right:-2px}.flyout.left{right:auto;left:-2px}.flyout.up{top:auto;bottom:39px}ul.flyout,.nav-bar li ul{padding:0;list-style:none}ul.flyout li,.nav-bar li ul li{border-left:solid 3px #CCC}ul.flyout li a,.nav-bar li ul li a{background:#f2f2f2;border:1px solid #e6e6e6;border-width:1px 1px 0 0;color:#555;display:block;font-size:14px;height:auto;line-height:1;padding:15px 20px;-webkit-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;-moz-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;box-shadow:0 1px 0 rgba(255,255,255,0.5) inset}ul.flyout li a:hover,ul.flyout li a:focus,.nav-bar li ul li a:hover,.nav-bar li ul li a:focus{background:#ebebeb;color:#333}ul.flyout li.active,.nav-bar li ul li.active{margin-top:0;border-top:1px solid #4d4d4d;border-left:4px solid #1a1a1a}ul.flyout li.active a,.nav-bar li ul li.active a{background:#4d4d4d;border:none;color:#fff;height:auto;margin:0;position:static;top:0;-webkit-box-shadow:0 0 0;-moz-box-shadow:0 0 0;box-shadow:0 0 0}.orbit-wrapper{width:1px;height:1px;position:relative}.orbit{width:1px;height:1px;position:relative;overflow:hidden;margin-bottom:17px}.orbit.with-bullets{margin-bottom:40px}.orbit .orbit-slide{max-width:100%;position:absolute;top:0;left:0}.orbit a.orbit-slide{border:none;line-height:0;display:none}.orbit div.orbit-slide{width:100%;height:100%;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0);opacity:0}.orbit-wrapper .timer{width:40px;height:40px;overflow:hidden;position:absolute;top:10px;right:10px;opacity:.6;cursor:pointer;z-index:31}.orbit-wrapper span.rotator{display:block;width:40px;height:40px;position:absolute;top:0;left:-20px;background:url('../images/foundation/orbit/rotator-black.png') no-repeat;z-index:3}.orbit-wrapper span.rotator.move{left:0}.orbit-wrapper span.mask{display:block;width:20px;height:40px;position:absolute;top:0;right:0;z-index:2;overflow:hidden}.orbit-wrapper span.mask.move{width:40px;left:0;background:url('../images/foundation/orbit/timer-black.png') repeat 0 0}.orbit-wrapper span.pause{display:block;width:40px;height:40px;position:absolute;top:0;left:0;background:url('../images/foundation/orbit/pause-black.png') no-repeat;z-index:4;opacity:0}.orbit-wrapper span.pause.active{background:url('../images/foundation/orbit/pause-black.png') no-repeat 0 -40px}.orbit-wrapper .timer:hover span.pause,.orbit-wrapper .timer:focus span.pause,.orbit-wrapper span.pause.active{opacity:1}.orbit-caption{display:none;font-family:inherit}.orbit-wrapper .orbit-caption{background:#000;background:rgba(0,0,0,0.6);z-index:30;color:#fff;text-align:center;padding:7px 0;font-size:13px;position:absolute;right:0;bottom:0;width:100%}.orbit-wrapper .slider-nav{display:block}.orbit-wrapper .slider-nav span{width:39px;height:50px;text-indent:-9999px;position:absolute;z-index:30;top:50%;margin-top:-25px;cursor:pointer}.orbit-wrapper .slider-nav span.right{background:url('../images/foundation/orbit/right-arrow.png');background-size:100%;right:0}.orbit-wrapper .slider-nav span.left{background:url('../images/foundation/orbit/left-arrow.png');background-size:100%;left:0}.lt-ie9 .orbit-wrapper .slider-nav span.right{background:url('../images/foundation/orbit/right-arrow-small.png')}.lt-ie9 .orbit-wrapper .slider-nav span.left{background:url('../images/foundation/orbit/left-arrow-small.png')}ul.orbit-bullets{position:absolute;z-index:30;list-style:none;bottom:-40px;left:50%;margin-left:-50px;padding:0}ul.orbit-bullets li{float:left;margin-left:5px;cursor:pointer;color:#999;text-indent:-9999px;background:url('../images/foundation/orbit/bullets.jpg') no-repeat 4px 0;width:13px;height:12px;overflow:hidden}ul.orbit-bullets li.active{color:#222;background-position:-8px 0}ul.orbit-bullets li.has-thumb{background:none;width:100px;height:75px}ul.orbit-bullets li.active.has-thumb{background-position:0 0;border-top:2px solid #000}.orbit-slide-counter{position:absolute;bottom:0;z-index:99;background:rgba(0,0,0,0.7);color:#fff;padding:5px}.orbit img.fluid-placeholder{visibility:hidden;position:static;display:block;width:100%}.orbit,.orbit-wrapper{width:100% !important}.lt-ie9 .timer{display:none !important}.lt-ie9 .orbit-caption{background:#000;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000,endColorstr=#99000000);zoom:1}@media only screen and (max-width: 767px){.orbit.orbit-stack-on-small img.fluid-placeholder{visibility:visible}.orbit.orbit-stack-on-small .orbit-slide{position:static;margin-bottom:10px}}.reveal-modal-bg{position:fixed;height:100%;width:100%;background:#000;background:rgba(0,0,0,0.45);z-index:40;display:none;top:0;left:0}.reveal-modal{background:#fff;visibility:hidden;display:none;top:100px;left:50%;margin-left:-260px;width:520px;position:absolute;z-index:41;padding:30px;-webkit-box-shadow:0 0 10px rgba(0,0,0,0.4);-moz-box-shadow:0 0 10px rgba(0,0,0,0.4);box-shadow:0 0 10px rgba(0,0,0,0.4)}.reveal-modal .close-reveal-modal:not(.button){font-size:22px;font-size:2.2rem;line-height:.5;position:absolute;top:8px;right:11px;color:#aaa;text-shadow:0 -1px 1px rgba(0,0,0,0.6);font-weight:bold;cursor:pointer}.reveal-modal.small{width:30%;margin-left:-15%}.reveal-modal.medium{width:40%;margin-left:-20%}.reveal-modal.large{width:60%;margin-left:-30%}.reveal-modal.xlarge{width:70%;margin-left:-35%}.reveal-modal.expand{width:90%;margin-left:-45%}.reveal-modal .row{min-width:0;margin-bottom:10px}.reveal-modal>:first-child{margin-top:0}.reveal-modal>:last-child{margin-bottom:0}@media print{.reveal-modal{border:solid 1px #000;background:#fff}}.tabs{list-style:none;border-bottom:solid 1px #e6e6e6;display:block;height:40px;padding:0;margin-bottom:20px}.tabs.contained{margin-bottom:0;margin-left:0}.tabs dt,.tabs li.section-title{color:#b3b3b3;cursor:default;display:block;float:left;font-size:12px;height:40px;line-height:40px;padding:0;padding-right:9px;padding-left:20px;font-weight:normal;width:auto;text-transform:uppercase}.tabs dt:first-child,.tabs li.section-title:first-child{padding:0;padding-right:9px}.tabs dd,.tabs li{display:block;float:left;padding:0;margin:0}.tabs dd a,.tabs li a{color:#6f6f6f;display:block;font-size:14px;height:40px;line-height:40px;padding:0px 23.8px}.tabs dd a:focus,.tabs li a:focus{font-weight:bold;color:#2ba6cb}.tabs dd.active,.tabs li.active{border-top:3px solid #2ba6cb;margin-top:-3px}.tabs dd.active a,.tabs li.active a{cursor:default;color:#3c3c3c;background:#fff;border-left:1px solid #e6e6e6;border-right:1px solid #e6e6e6;font-weight:bold}.tabs dd:first-child,.tabs li:first-child{margin-left:0}.tabs.vertical{height:auto;border-bottom:1px solid #e6e6e6}.tabs.vertical dt,.tabs.vertical dd,.tabs.vertical li{float:none;height:auto}.tabs.vertical dd,.tabs.vertical li{border-left:3px solid #ccc}.tabs.vertical dd a,.tabs.vertical li a{background:#f2f2f2;border:none;border:1px solid #e6e6e6;border-width:1px 1px 0 0;color:#555;display:block;font-size:14px;height:auto;line-height:1;padding:15px 20px;-webkit-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;-moz-box-shadow:0 1px 0 rgba(255,255,255,0.5) inset;box-shadow:0 1px 0 rgba(255,255,255,0.5) inset}.tabs.vertical dd.active,.tabs.vertical li.active{margin-top:0;border-top:1px solid #4d4d4d;border-left:4px solid #1a1a1a}.tabs.vertical dd.active a,.tabs.vertical li.active a{background:#4d4d4d;border:none;color:#fff;height:auto;margin:0;position:static;top:0;-webkit-box-shadow:0 0 0;-moz-box-shadow:0 0 0;box-shadow:0 0 0}.tabs.vertical dd:first-child a.active,.tabs.vertical li:first-child a.active{margin:0}.tabs.pill{border-bottom:none;margin-bottom:10px}.tabs.pill dd,.tabs.pill li{margin-right:10px}.tabs.pill dd:last-child,.tabs.pill li:last-child{margin-right:0}.tabs.pill dd a,.tabs.pill li a{-webkit-border-radius:1000px;-moz-border-radius:1000px;-ms-border-radius:1000px;-o-border-radius:1000px;border-radius:1000px;background:#e6e6e6;height:26px;line-height:26px;color:#666}.tabs.pill dd.active,.tabs.pill li.active{border:none;margin-top:0}.tabs.pill dd.active a,.tabs.pill li.active a{background-color:#2ba6cb;border:none;color:#fff}.tabs.pill.contained{border-bottom:solid 1px #eee;margin-bottom:0}.tabs.pill.two-up dd,.tabs.pill.two-up li,.tabs.pill.three-up dd,.tabs.pill.three-up li,.tabs.pill.four-up dd,.tabs.pill.four-up li,.tabs.pill.five-up dd,.tabs.pill.five-up li{margin-right:0}.tabs.two-up dt a,.tabs.two-up dd a,.tabs.two-up li a,.tabs.three-up dt a,.tabs.three-up dd a,.tabs.three-up li a,.tabs.four-up dt a,.tabs.four-up dd a,.tabs.four-up li a,.tabs.five-up dt a,.tabs.five-up dd a,.tabs.five-up li a{padding:0 17px;text-align:center;overflow:hidden}.tabs.two-up dt,.tabs.two-up dd,.tabs.two-up li{width:50%}.tabs.three-up dt,.tabs.three-up dd,.tabs.three-up li{width:33.33%}.tabs.four-up dt,.tabs.four-up dd,.tabs.four-up li{width:25%}.tabs.five-up dt,.tabs.five-up dd,.tabs.five-up li{width:20%}ul.tabs-content{display:block;margin:0 0 20px;padding:0}ul.tabs-content>li{display:none}ul.tabs-content>li.active{display:block}ul.tabs-content.contained{padding:0}ul.tabs-content.contained>li{border:solid 0 #e6e6e6;border-width:0 1px 1px 1px;padding:20px}ul.tabs-content.contained.vertical>li{border-width:1px 1px 1px 1px}.no-js ul.tabs-content>li{display:block}div.alert-box{display:block;padding:6px 7px 7px;font-weight:bold;font-size:14px;color:#fff;background-color:#2ba6cb;border:1px solid rgba(0,0,0,0.1);margin-bottom:12px;-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:3px;text-shadow:0 -1px rgba(0,0,0,0.3);position:relative}div.alert-box.success{background-color:#5da423;color:#fff;text-shadow:0 -1px rgba(0,0,0,0.3)}div.alert-box.alert{background-color:#c60f13;color:#fff;text-shadow:0 -1px rgba(0,0,0,0.3)}div.alert-box.secondary{background-color:#e9e9e9;color:#505050;text-shadow:0 1px rgba(255,255,255,0.3)}div.alert-box a.close{color:#333;position:absolute;right:4px;top:-1px;font-size:17px;opacity:0.2;padding:4px}div.alert-box a.close:hover,div.alert-box a.close:focus{opacity:0.4}.label{padding:1px 4px 2px;font-size:12px;font-weight:bold;text-align:center;text-decoration:none;line-height:1;white-space:nowrap;display:inline;position:relative;bottom:1px;color:#fff;background:#2ba6cb}.label.radius{-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:3px}.label.round{padding:1px 7px 2px;-webkit-border-radius:1000px;-moz-border-radius:1000px;-ms-border-radius:1000px;-o-border-radius:1000px;border-radius:1000px}.label.alert{background-color:#c60f13}.label.success{background-color:#5da423}.label.secondary{background-color:#e9e9e9;color:#505050}.has-tip{border-bottom:dotted 1px #ccc;cursor:help;font-weight:bold;color:#333}.has-tip:hover,.has-tip:focus{border-bottom:dotted 1px #196177;color:#2ba6cb}.has-tip.tip-left,.has-tip.tip-right{float:none !important}.tooltip{display:none;background:#000;background:rgba(0,0,0,0.85);position:absolute;color:#fff;font-weight:bold;font-size:12px;padding:5px;z-index:999;-webkit-border-radius:4px;-moz-border-radius:4px;-ms-border-radius:4px;-o-border-radius:4px;border-radius:4px;line-height:normal}.tooltip>.nub{display:block;width:0;height:0;border:solid 5px;border-color:transparent transparent #000 transparent;border-color:transparent transparent rgba(0,0,0,0.85) transparent;position:absolute;top:-10px;left:10px}.tooltip.tip-override>.nub{border-color:transparent transparent #000 transparent !important;border-color:transparent transparent rgba(0,0,0,0.85) transparent !important;top:-10px !important}.tooltip.tip-top>.nub,.tooltip.tip-centered-top>.nub{border-color:#000 transparent transparent transparent;border-color:rgba(0,0,0,0.85) transparent transparent transparent;top:auto;bottom:-10px}.tooltip.tip-left,.tooltip.tip-right{float:none !important}.tooltip.tip-left>.nub{border-color:transparent transparent transparent #000;border-color:transparent transparent transparent rgba(0,0,0,0.85);right:-10px;left:auto}.tooltip.tip-right>.nub{border-color:transparent #000 transparent transparent;border-color:transparent rgba(0,0,0,0.85) transparent transparent;right:auto;left:-10px}.tooltip.noradius{-webkit-border-radius:0;-moz-border-radius:0;-ms-border-radius:0;-o-border-radius:0;border-radius:0}.tooltip.opened{color:#2ba6cb !important;border-bottom:dotted 1px #196177 !important}.tap-to-close{display:block;font-size:10px;font-size:1rem;color:#888;font-weight:normal}.panel{background:#f2f2f2;border:solid 1px #e6e6e6;margin:0 0 22px 0;padding:20px}.panel>:first-child{margin-top:0}.panel>:last-child{margin-bottom:0}.panel.callout{background:#2ba6cb;color:#fff;border-color:#2284a1;-webkit-box-shadow:inset 0px 1px 0px rgba(255,255,255,0.5);-moz-box-shadow:inset 0px 1px 0px rgba(255,255,255,0.5);box-shadow:inset 0px 1px 0px rgba(255,255,255,0.5)}.panel.callout a{color:#fff}.panel.callout .button{background:#fff;border:none;color:#2ba6cb;text-shadow:none}.panel.callout .button:hover,.panel.callout .button:focus{background:rgba(255,255,255,0.8)}.panel.radius{-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:3px}ul.accordion{margin:0 0 22px 0;border-bottom:1px solid #e9e9e9}ul.accordion>li{list-style:none;margin:0;padding:0;border-top:1px solid #e9e9e9}ul.accordion>li>div.title{cursor:pointer;background:#f6f6f6;padding:15px;margin:0;position:relative;border-left:1px solid #e9e9e9;border-right:1px solid #e9e9e9;-webkit-transition:0.15s background linear;-moz-transition:0.15s background linear;-o-transition:0.15s background linear;transition:0.15s background linear}ul.accordion>li>div.title h1,ul.accordion>li>div.title h2,ul.accordion>li>div.title h3,ul.accordion>li>div.title h4,ul.accordion>li>div.title h5{margin:0}ul.accordion>li>div.title:after{content:"";display:block;width:0;height:0;border:solid 6px;border-color:transparent #9d9d9d transparent transparent;position:absolute;right:15px;top:21px}ul.accordion>li .content{display:none;padding:15px}ul.accordion>li.active{border-top:3px solid #2ba6cb}ul.accordion>li.active .title{background:#fff;padding-top:13px}ul.accordion>li.active .title:after{content:"";display:block;width:0;height:0;border:solid 6px;border-color:#9d9d9d transparent transparent transparent}ul.accordion>li.active .content{background:#fff;display:block;border-left:1px solid #e9e9e9;border-right:1px solid #e9e9e9}ul.side-nav{display:block;list-style:none;margin:0;padding:17px 0}ul.side-nav li{display:block;list-style:none;margin:0 0 7px 0}ul.side-nav li a{display:block}ul.side-nav li.active a{color:#4d4d4d;font-weight:bold}ul.side-nav li.divider{border-top:1px solid #e6e6e6;height:0;padding:0}dl.sub-nav{display:block;width:auto;overflow:hidden;margin:-4px 0 18px;margin-right:0;margin-left:-9px;padding-top:4px}dl.sub-nav dt,dl.sub-nav dd{float:left;display:inline;margin-left:9px;margin-bottom:10px}dl.sub-nav dt{color:#999;font-weight:normal}dl.sub-nav dd a{text-decoration:none;-webkit-border-radius:1000px;-moz-border-radius:1000px;-ms-border-radius:1000px;-o-border-radius:1000px;border-radius:1000px}dl.sub-nav dd.active a{font-weight:bold;background:#2ba6cb;color:#fff;padding:3px 9px;cursor:default}ul.pagination{display:block;height:24px;margin-left:-5px}ul.pagination li{float:left;display:block;height:24px;color:#999;font-size:14px;margin-left:5px}ul.pagination li a{display:block;padding:1px 7px 1px;color:#555}ul.pagination li:hover a,ul.pagination li a:focus{background:#e6e6e6}ul.pagination li.unavailable a{cursor:default;color:#999}ul.pagination li.unavailable:hover a,ul.pagination li.unavailable a:focus{background:transparent}ul.pagination li.current a{background:#2ba6cb;color:#fff;font-weight:bold;cursor:default}ul.pagination li.current a:hover,ul.pagination li.current a:focus{background:#2ba6cb}div.pagination-centered{text-align:center}div.pagination-centered ul>li{float:none;display:inline-block}ul.breadcrumbs{display:block;background:#f6f6f6;padding:6px 10px 7px;border:1px solid #e9e9e9;-webkit-border-radius:2px;-moz-border-radius:2px;-ms-border-radius:2px;-o-border-radius:2px;border-radius:2px;overflow:hidden;margin-left:0}ul.breadcrumbs li{margin:0;padding:0 12px 0 0;float:left;list-style:none}ul.breadcrumbs li a,ul.breadcrumbs li span{text-transform:uppercase;font-size:11px;font-size:1.1rem;padding-left:12px}ul.breadcrumbs li:first-child a,ul.breadcrumbs li:first-child span{padding-left:0}ul.breadcrumbs li:before{content:"/";color:#aaa}ul.breadcrumbs li:first-child:before{content:" "}ul.breadcrumbs li.current a{cursor:default;color:#333}ul.breadcrumbs li:hover a,ul.breadcrumbs li a:focus{text-decoration:underline}ul.breadcrumbs li.current:hover a,ul.breadcrumbs li.current a:focus{text-decoration:none}ul.breadcrumbs li.unavailable a{color:#999}ul.breadcrumbs li.unavailable:hover a,ul.breadcrumbs li.unavailable a:focus{text-decoration:none;color:#999;cursor:default}ul.inline-list,ul.link-list{margin:0 0 17px -22px;padding:0;list-style:none;overflow:hidden}ul.inline-list>li,ul.link-list>li{list-style:none;float:left;margin-left:22px;display:block}ul.inline-list>li>*,ul.link-list>li>*{display:block}.keystroke,kbd{font-family:"Consolas", "Menlo", "Courier", monospace;font-size:13px;padding:2px 4px 0px;margin:0;background:#ededed;border:solid 1px #dbdbdb;-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:3px}.th{display:block}.th img{display:block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px rgba(0,0,0,0.2);-moz-box-shadow:0 0 0 1px rgba(0,0,0,0.2);box-shadow:0 0 0 1px rgba(0,0,0,0.2);-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:3px;-webkit-transition-property:box-shadow;-moz-transition-property:box-shadow;-o-transition-property:box-shadow;transition-property:box-shadow;-webkit-transition-duration:300ms;-moz-transition-duration:300ms;-o-transition-duration:300ms;transition-duration:300ms}.th:hover img,.th:focus img{-webkit-box-shadow:0 0 6px 1px rgba(43,166,203,0.5);-moz-box-shadow:0 0 6px 1px rgba(43,166,203,0.5);box-shadow:0 0 6px 1px rgba(43,166,203,0.5)}.flex-video{position:relative;padding-top:25px;padding-bottom:67.5%;height:0;margin-bottom:16px;overflow:hidden}.flex-video.widescreen{padding-bottom:57.25%}.flex-video.vimeo{padding-top:0}.flex-video iframe,.flex-video object,.flex-video embed,.flex-video video{position:absolute;top:0;left:0;width:100%;height:100%}table{background:#fff;-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:3px;margin:0 0 18px;border:1px solid #ddd}table thead,table tfoot{background:#f5f5f5}table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;font-size:14px;line-height:18px;text-align:left}table thead tr th,table tfoot tr td{padding:8px 10px 9px;font-size:14px;font-weight:bold;color:#222}table thead tr th:first-child,table tfoot tr td:first-child{border-left:none}table thead tr th:last-child,table tfoot tr td:last-child{border-right:none}table tbody tr.even,table tbody tr.alt{background:#f9f9f9}table tbody tr:nth-child(even){background:#f9f9f9}table tbody tr td{color:#333;padding:9px 10px;vertical-align:top;border:none}ul.vcard{display:inline-block;margin:0 0 12px 0;border:1px solid #ddd;padding:10px}ul.vcard li{margin:0;display:block}ul.vcard li.fn{font-weight:bold;font-size:15px}p.vevent span.summary{font-weight:bold}p.vevent abbr{cursor:default;text-decoration:none;font-weight:bold;border:none;padding:0 1px}div.progress{padding:2px;margin-bottom:10px;border:1px solid #ccc;height:25px}div.progress .meter{background:#2ba6cb;height:100%;display:block;width:50%}div.progress.secondary .meter{background:#e9e9e9}div.progress.success .meter{background:#5da423}div.progress.alert .meter{background:#c60f13}div.progress.radius{-webkit-border-radius:3px;-moz-border-radius:3px;-ms-border-radius:3px;-o-border-radius:3px;border-radius:3px}div.progress.radius .meter{-webkit-border-radius:2px;-moz-border-radius:2px;-ms-border-radius:2px;-o-border-radius:2px;border-radius:2px}div.progress.round{-webkit-border-radius:1000px;-moz-border-radius:1000px;-ms-border-radius:1000px;-o-border-radius:1000px;border-radius:1000px}div.progress.round .meter{-webkit-border-radius:1000px;-moz-border-radius:1000px;-ms-border-radius:1000px;-o-border-radius:1000px;border-radius:1000px}.pricing-table{border:solid 1px #ddd;margin-left:0;margin-bottom:20px}.pricing-table *{list-style:none;line-height:1}.pricing-table .title{background-color:#ddd;padding:15px 20px;text-align:center;color:#333;font-weight:bold;font-size:16px}.pricing-table .price{background-color:#eee;padding:15px 20px;text-align:center;color:#333;font-weight:normal;font-size:20px}.pricing-table .description{background-color:#fff;padding:15px;text-align:center;color:#777;font-size:12px;font-weight:normal;line-height:1.4;border-bottom:dotted 1px #ddd}.pricing-table .bullet-item{background-color:#fff;padding:15px;text-align:center;color:#333;font-size:14px;font-weight:normal;border-bottom:dotted 1px #ddd}.pricing-table .cta-button{background-color:#f5f5f5;text-align:center;padding:20px}.top-bar-js-breakpoint{width:940px !important;visibility:hidden}.contain-to-grid{width:100%;background:#222}.fixed{width:100%;left:0;position:fixed;top:0;z-index:99}.sticky{float:left;overflow:hidden}.sticky.fixed{float:none}.top-bar{background:#222;min-height:45px;line-height:45px;margin:0 0 30px 0;padding:0;width:100%;position:relative}.contain-to-grid .top-bar{max-width:940px;margin:0 auto}.top-bar>ul .name h1{line-height:45px;margin:0}.top-bar>ul .name h1 a{font-weight:bold;padding:0 22.5px;font-size:17px !important}.top-bar>ul .name img{margin-top:-5px;vertical-align:middle}.top-bar.expanded{height:inherit}.top-bar ul{margin-left:0;display:inline;height:45px;line-height:45px;list-style:none}.top-bar ul>li{float:left}.top-bar ul>li a:not(.button){color:#fff;display:block;font-size:13px;font-weight:bold;height:45px;line-height:45px;padding:0 15px}.top-bar ul>li:not(.name):hover,.top-bar ul>li:not(.name).active,.top-bar ul>li:not(.name):focus{background:#000}.top-bar ul>li:not(.name):hover a,.top-bar ul>li:not(.name).active a,.top-bar ul>li:not(.name):focus a{color:#d9d9d9}.top-bar ul>li.divider{background:#000;-webkit-box-shadow:1px 0 0 rgba(255,255,255,0.1);-moz-box-shadow:1px 0 0 rgba(255,255,255,0.1);box-shadow:1px 0 0 rgba(255,255,255,0.1);height:100%;margin-right:1px;width:1px}.top-bar ul>li.has-button a.button{margin:0 11.25px}.top-bar ul>li.has-button:hover,.top-bar ul>li.has-button:focus{background:#222}.top-bar ul>li.has-button:hover a,.top-bar ul>li.has-button:focus a{color:#fff}.top-bar ul>li.search{padding:0 15px}.top-bar ul>li.search form{display:inline-block;margin-bottom:0;vertical-align:middle;width:200px}.top-bar ul>li.search form input[type=text]{-moz-border-radius-topright:0;-webkit-border-top-right-radius:0;border-top-right-radius:0;-moz-border-radius-bottomright:0;-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;float:left;font-size:13px;margin-top:-1px;height:22.5px;margin-bottom:0;width:130px}.top-bar ul>li.search form input[type=text]+.button{border-left:none;-moz-border-radius-topleft:0;-webkit-border-top-left-radius:0;border-top-left-radius:0;-moz-border-radius-bottomleft:0;-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;float:left;font-size:12px;margin-top:-1px;padding:5px 12px 4px}.top-bar ul>li.search form input[type=search]{font-size:16px;margin-bottom:0}.top-bar ul>li.search:hover,.top-bar ul>li.search:focus{background:#222}.top-bar ul>li.login{padding:0 15px}.top-bar ul>li.login form{display:inline-block;margin-bottom:0;vertical-align:middle;width:300px}.top-bar ul>li.login form input{float:left;width:auto;font-size:13px;margin-top:-1px;height:22.5px;margin-bottom:0}.top-bar ul>li.login form input[type=text]{-moz-border-radius-topright:0;-webkit-border-top-right-radius:0;border-top-right-radius:0;-moz-border-radius-bottomright:0;-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;width:120px}.top-bar ul>li.login form input[type=password]{margin-bottom:0;-moz-border-radius-topleft:0;-webkit-border-top-left-radius:0;border-top-left-radius:0;-moz-border-radius-bottomleft:0;-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;width:120px}.top-bar ul>li.login form input[type=password]+.button{border-left:none;-moz-border-radius-topleft:0;-webkit-border-top-left-radius:0;border-top-left-radius:0;-moz-border-radius-bottomleft:0;-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-topright:2px;-webkit-border-top-right-radius:2px;border-top-right-radius:2px;-moz-border-radius-bottomright:2px;-webkit-border-bottom-right-radius:2px;border-bottom-right-radius:2px;float:left;font-size:12px;margin-top:-1px;padding:5px 12px 4px;width:60px}.top-bar ul>li.login:hover,.top-bar ul>li.login:focus{background:#222}.top-bar ul>li.toggle-topbar{display:none}.top-bar ul>li.has-dropdown{position:relative}.top-bar ul>li.has-dropdown:hover>.dropdown,.top-bar ul>li.has-dropdown:focus>.dropdown{display:block;visibility:visible}.top-bar ul>li.has-dropdown a{padding-right:33.75px}.top-bar ul>li.has-dropdown a:after{content:"";display:block;width:0;height:0;border:solid 5px;border-color:#fff transparent transparent transparent;margin-right:15px;margin-top:-2.5px;position:absolute;right:0;top:50%}.top-bar ul>li.has-dropdown .dropdown{background:#222;left:0;margin:0;padding:9px 0 0 0;position:absolute;visibility:hidden;z-index:99}.top-bar ul>li.has-dropdown .dropdown li{background:#222;line-height:1;min-width:100%;padding-bottom:5px}.top-bar ul>li.has-dropdown .dropdown li a{color:#fff;font-weight:normal;height:100%;line-height:1;padding:5px 17px 5px 15px;white-space:nowrap}.top-bar ul>li.has-dropdown .dropdown li a:after{border:none}.top-bar ul>li.has-dropdown .dropdown li a:hover,.top-bar ul>li.has-dropdown .dropdown li a:focus{background:#3c3c3c}.top-bar ul>li.has-dropdown .dropdown li label{color:#6f6f6f;font-size:10px;font-weight:bold;margin:0;padding-left:15px;text-transform:uppercase}.top-bar ul>li.has-dropdown .dropdown li.divider{border-top:solid 1px #000;-webkit-box-shadow:0 1px 0 rgba(255,255,255,0.1) inset;-moz-box-shadow:0 1px 0 rgba(255,255,255,0.1) inset;box-shadow:0 1px 0 rgba(255,255,255,0.1) inset;height:10px;padding:0;width:100%}.top-bar ul>li.has-dropdown .dropdown li:last-child{padding-bottom:10px}.top-bar ul>li.has-dropdown .dropdown li.active a{background:#000}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown>a{padding-right:30px}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown>a:after{border:none;content:"\00bb";right:5px;top:6px}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown .dropdown{position:absolute;left:100%;top:0}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown:hover>.dropdown,.top-bar ul>li.has-dropdown .dropdown li.has-dropdown:focus>.dropdown{display:block}.top-bar ul.left{float:left;width:auto;margin-bottom:0}.top-bar ul.right{float:right;width:auto;margin-bottom:0}.top-bar ul.right .has-dropdown .dropdown{left:auto;right:0px}.top-bar ul.right .has-dropdown .dropdown li.has-dropdown>.dropdown{right:100%;left:auto;width:100%}.top-bar .js-generated{display:none}@-moz-document url-prefix(){.top-bar ul li .button.small{padding-bottom:6px}.top-bar ul li.search form input[type=search]{font-size:14px;height:22px;padding:3px}}.lt-ie9 .top-bar ul li a{color:#fff;display:block;font-weight:bold;font-size:13px;height:45px;line-height:45px;padding:0 15px}.lt-ie9 .top-bar ul li a.button{height:auto;line-height:30px;margin-top:7px}.lt-ie9 .top-bar ul li a img{margin-top:-5px;vertical-align:middle}.lt-ie9 .top-bar section>ul>li a:hover,.lt-ie9 .top-bar section>ul>li a:focus{color:#ccc}.lt-ie9 .top-bar section>ul>li:hover,.lt-ie9 .top-bar section>ul>li:focus{background:#000}.lt-ie9 .top-bar section>ul>li.search:hover,.lt-ie9 .top-bar section>ul>li.search:focus,.lt-ie9 .top-bar section>ul>li.has-button:hover,.lt-ie9 .top-bar section>ul>li.has-button:focus{background:none}.lt-ie9 .top-bar section>ul>li.active{background:#000;color:#d9d9d9}.lt-ie9 .top-bar ul li.has-dropdown{padding-right:33.75px}.lt-ie9 .top-bar ul li.has-dropdown>ul li{padding-right:0}#joyRideTipContent{display:none}.joyride-tip-guide{display:none;position:absolute;background:#000;background:rgba(0,0,0,0.8);color:#fff;width:300px;z-index:101;top:0;left:0;font-family:inherit;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;-ms-border-radius:4px;-o-border-radius:4px;border-radius:4px}.joyride-content-wrapper{padding:18px 20px 24px}.joyride-tip-guide span.joyride-nub{display:block;position:absolute;left:22px;width:0;height:0;border:solid 14px}.joyride-tip-guide span.joyride-nub.top{border-color:#000;border-color:rgba(0,0,0,0.8);border-top-color:transparent !important;border-left-color:transparent !important;border-right-color:transparent !important;top:-28px;bottom:none}.joyride-tip-guide span.joyride-nub.bottom{border-color:#000;border-color:rgba(0,0,0,0.8) !important;border-bottom-color:transparent !important;border-left-color:transparent !important;border-right-color:transparent !important;bottom:-28px;bottom:none}.joyride-tip-guide span.joyride-nub.right{border-color:#000;border-color:rgba(0,0,0,0.8) !important;border-top-color:transparent !important;border-right-color:transparent !important;border-bottom-color:transparent !important;top:22px;bottom:none;left:auto;right:-28px}.joyride-tip-guide span.joyride-nub.left{border-color:#000;border-color:rgba(0,0,0,0.8) !important;border-top-color:transparent !important;border-left-color:transparent !important;border-bottom-color:transparent !important;top:22px;left:-28px;right:auto;bottom:none}.joyride-tip-guide h1,.joyride-tip-guide h2,.joyride-tip-guide h3,.joyride-tip-guide h4,.joyride-tip-guide h5,.joyride-tip-guide h6{line-height:1.25;margin:0;font-weight:bold;color:#fff}.joyride-tip-guide p{margin:0 0 18px 0;font-size:14px;line-height:1.3}.joyride-timer-indicator-wrap{width:50px;height:3px;border:solid 1px #555;position:absolute;right:17px;bottom:16px}.joyride-timer-indicator{display:block;width:0;height:inherit;background:#666}.joyride-close-tip{position:absolute;right:10px;top:10px;color:#777 !important;text-decoration:none;font-size:20px;font-weight:normal;line-height:.5 !important}.joyride-close-tip:hover,.joyride-close-tip:focus{color:#eee !important}.joyride-modal-bg{position:fixed;height:100%;width:100%;background:transparent;background:rgba(0,0,0,0.5);z-index:100;display:none;top:0;left:0;cursor:pointer}.clearing-blackout{background:#000;background:rgba(0,0,0,0.8);position:fixed;width:100%;height:100%;top:0;left:0;z-index:999}.clearing-blackout .clearing-close{display:block}.clearing-container{position:relative;z-index:999;height:100%;overflow:hidden}.visible-img{height:75%;position:relative}.visible-img img{position:absolute;left:50%;top:50%;margin-left:-50%;max-height:100%;max-width:100%}.visible-img .clearing-caption{color:#fff;margin-bottom:0;text-align:center;position:absolute;bottom:0;background:#000;background:rgba(0,0,0,0.7);width:100%;padding:10px 100px}.clearing-close{z-index:999;position:absolute;top:10px;right:20px;font-size:30px;line-height:1;color:#fff;display:none}.clearing-close:hover,.clearing-close:focus{color:#ccc}.clearing-main-left,.clearing-main-right{position:absolute;top:50%;margin-top:-16px}.clearing-main-left.disabled,.clearing-main-right.disabled{opacity:0.5}.clearing-main-left:active,.clearing-main-right:active{margin-top:-15px}.clearing-main-left{left:10px;content:"";display:block;width:0;height:0;border:solid 16px;border-color:transparent #fff transparent transparent}.clearing-main-right{right:10px;content:"";display:block;width:0;height:0;border:solid 16px;border-color:transparent transparent transparent #fff}ul[data-clearing].block-grid.three-up>li:nth-child(3n+1){clear:none}ul[data-clearing] li{cursor:pointer;display:block}ul[data-clearing] li.clearing-feature ~ li{display:none}.clearing-assembled .clearing-container .carousel{background:#000;background:rgba(0,0,0,0.75);height:150px;margin-top:5px}.clearing-assembled .clearing-container .visible-img{background:#000;background:rgba(0,0,0,0.75);overflow:hidden}.clearing-assembled .clearing-container ul[data-clearing]{z-index:999;width:200%;height:100%;margin-left:0;position:relative;left:0}.clearing-assembled .clearing-container ul[data-clearing] li{display:block;width:175px;height:inherit;padding:0;float:left;overflow:hidden;background:#222;margin-right:1px;position:relative}.clearing-assembled .clearing-container ul[data-clearing] li.fix-height img{min-height:100%;height:100%;max-width:none}.clearing-assembled .clearing-container ul[data-clearing] li img{cursor:pointer !important;min-width:100% !important}.clearing-assembled .clearing-container ul[data-clearing] li.visible{border-top:4px solid #fff}ul.block-grid[data-clearing]{overflow:visible}.clearing-blackout ul.block-grid[data-clearing].two-up>li:nth-child(2n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].three-up>li:nth-child(3n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].four-up>li:nth-child(4n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].five-up>li:nth-child(5n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].six-up>li:nth-child(6n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].seven-up>li:nth-child(7n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].eight-up>li:nth-child(8n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].nine-up>li:nth-child(9n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].ten-up>li:nth-child(10n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].eleven-up>li:nth-child(11n+1){clear:none}.clearing-blackout ul.block-grid[data-clearing].twelve-up>li:nth-child(12n+1){clear:none}.clearing-blackout .th img{border:none;-webkit-box-shadow:0 0 0 0 rgba(0,0,0,0);-moz-box-shadow:0 0 0 0 rgba(0,0,0,0);box-shadow:0 0 0 0 rgba(0,0,0,0);-webkit-border-radius:0;-moz-border-radius:0;-ms-border-radius:0;-o-border-radius:0;border-radius:0}.clearing-blackout:hover img,.clearing-blackout:focus img{-webkit-box-shadow:0 0 0 0 rgba(0,0,0,0);-moz-box-shadow:0 0 0 0 rgba(0,0,0,0);box-shadow:0 0 0 0 rgba(0,0,0,0)}.show-for-small,.show-for-medium,.show-for-medium-down,.hide-for-large,.hide-for-large-up,.show-for-xlarge,.show-for-print{display:none !important}.hide-for-small,.hide-for-medium,.hide-for-medium-down,.show-for-large,.show-for-large-up,.hide-for-xlarge,.hide-for-print{display:inherit !important}@media only screen and (min-width: 1441px){.hide-for-small,.hide-for-medium,.hide-for-medium-down,.hide-for-large,.show-for-large-up,.show-for-xlarge{display:inherit !important}.show-for-small,.show-for-medium,.show-for-medium-down,.show-for-large,.hide-for-large-up,.hide-for-xlarge{display:none !important}}@media only screen and (max-width: 1279px) and (min-width: 768px){.hide-for-small,.show-for-medium,.show-for-medium-down,.hide-for-large,.hide-for-large-up,.hide-for-xlarge{display:inherit !important}.show-for-small,.hide-for-medium,.hide-for-medium-down,.show-for-large,.show-for-large-up,.show-for-xlarge{display:none !important}}@media only screen and (max-width: 767px){.show-for-small,.hide-for-medium,.show-for-medium-down,.hide-for-large,.hide-for-large-up,.hide-for-xlarge{display:inherit !important}.hide-for-small,.show-for-medium,.hide-for-medium-down,.show-for-large,.show-for-large-up,.show-for-xlarge{display:none !important}}.show-for-landscape,.hide-for-portrait{display:inherit !important}.hide-for-landscape,.show-for-portrait{display:none !important}@media screen and (orientation: landscape){.show-for-landscape,.hide-for-portrait{display:inherit !important}.hide-for-landscape,.show-for-portrait{display:none !important}}@media screen and (orientation: portrait){.show-for-portrait,.hide-for-landscape{display:inherit !important}.hide-for-portrait,.show-for-landscape{display:none !important}}.show-for-touch{display:none !important}.hide-for-touch{display:inherit !important}.touch .show-for-touch{display:inherit !important}.touch .hide-for-touch{display:none !important}table.show-for-xlarge,table.show-for-large,table.hide-for-small,table.hide-for-medium{display:table !important}@media only screen and (max-width: 1279px) and (min-width: 768px){.touch table.hide-for-xlarge,.touch table.hide-for-large,.touch table.hide-for-small,.touch table.show-for-medium{display:table !important}}@media only screen and (max-width: 767px){table.hide-for-xlarge,table.hide-for-large,table.hide-for-medium,table.show-for-small{display:table !important}}@media only screen and (max-device-width: 1280px){.touch .nav-bar li.has-flyout>a{padding-right:36px !important}}@media only screen and (max-device-width: 800px), only screen and (device-width: 1024px) and (device-height: 600px), only screen and (width: 1280px) and (orientation: landscape), only screen and (device-width: 800px), only screen and (max-width: 767px){.flex-video{padding-top:0}}@media only screen and (max-width: 1279px) and (min-width: 768px){.touch .nav-bar li a{font-size:13px}.touch .nav-bar li.has-flyout>a.flyout-toggle{padding:20px !important}.touch .nav-bar li.has-flyout>a{padding-right:36px !important}.clearing-main-right,.clearing-main-left{height:100%;width:40px;top:0;border:none}.clearing-main-right:before,.clearing-main-left:before{position:absolute;top:50%}.clearing-main-left{left:0}.clearing-main-left:before{left:5px;content:"";display:block;width:0;height:0;border:solid 16px;border-color:transparent #fff transparent transparent}.clearing-main-right{height:100%;right:0}.clearing-main-right:before{content:"";display:block;width:0;height:0;border:solid 16px;border-color:transparent transparent transparent #fff}}@media only screen and (max-width: 767px){.left,.right{float:none}body{-webkit-text-size-adjust:none;-ms-text-size-adjust:none;width:100%;min-width:0;margin-left:0;margin-right:0;padding-left:0;padding-right:0}.row{width:auto;min-width:0;margin-left:0;margin-right:0}.column,.columns{width:auto !important;float:none}.column:last-child,.columns:last-child{float:none}[class*="column"]+[class*="column"]:last-child{float:none}.column:before,.columns:before,.column:after,.columns:after{content:"";display:table}.column:after,.columns:after{clear:both}.offset-by-one,.offset-by-two,.offset-by-three,.offset-by-four,.offset-by-five,.offset-by-six,.offset-by-seven,.offset-by-eight,.offset-by-nine,.offset-by-ten{margin-left:0 !important}.push-two,.push-three,.push-four,.push-five,.push-six,.push-seven,.push-eight,.push-nine,.push-ten{left:auto}.pull-two,.pull-three,.pull-four,.pull-five,.pull-six,.pull-seven,.pull-eight,.pull-nine,.pull-ten{right:auto}.row .mobile-one{width:25% !important;float:left;padding:0 15px}.row .mobile-one:last-child{float:right}.row .mobile-one.end{float:left}.row.collapse .mobile-one{padding:0}.row .mobile-two{width:50% !important;float:left;padding:0 15px}.row .mobile-two:last-child{float:right}.row .mobile-two.end{float:left}.row.collapse .mobile-two{padding:0}.row .mobile-three{width:75% !important;float:left;padding:0 15px}.row .mobile-three:last-child{float:right}.row .mobile-three.end{float:left}.row.collapse .mobile-three{padding:0}.row .mobile-four{width:100% !important;float:left;padding:0 15px}.row .mobile-four:last-child{float:right}.row .mobile-four.end{float:left}.row.collapse .mobile-four{padding:0}.push-one-mobile{left:25%}.pull-one-mobile{right:25%}.push-two-mobile{left:50%}.pull-two-mobile{right:50%}.push-three-mobile{left:75%}.pull-three-mobile{right:75%}.block-grid.mobile>li{float:none;width:100%;margin-left:0}.block-grid>li{clear:none}.block-grid.mobile-one-up>li{width:100%}.block-grid.mobile-two-up>li{width:50%}.block-grid.mobile-two-up>li:nth-child(2n+1){clear:both}.block-grid.mobile-three-up>li{width:33.33333%}.block-grid.mobile-three-up>li:nth-child(3n+1){clear:both}.block-grid.mobile-four-up>li{width:25%}.block-grid.mobile-four-up>li:nth-child(4n+1){clear:both}.block-grid.mobile-five-up>li{width:20%}.block-grid.mobile-five-up>li:nth-child(5n+1){clear:both}.block-grid.mobile-six-up>li{width:16.66667%}.block-grid.mobile-six-up>li:nth-child(6n+1){clear:both}.block-grid.mobile-seven-up>li{width:14.28571%}.block-grid.mobile-seven-up>li:nth-child(7n+1){clear:both}.block-grid.mobile-eight-up>li{width:12.5%}.block-grid.mobile-eight-up>li:nth-child(8n+1){clear:both}.block-grid.mobile-nine-up>li{width:11.11111%}.block-grid.mobile-nine-up>li:nth-child(9n+1){clear:both}.block-grid.mobile-ten-up>li{width:10%}.block-grid.mobile-ten-up>li:nth-child(10n+1){clear:both}.block-grid.mobile-eleven-up>li{width:9.09091%}.block-grid.mobile-eleven-up>li:nth-child(11n+1){clear:both}.block-grid.mobile-twelve-up>li{width:8.33333%}.block-grid.mobile-twelve-up>li:nth-child(12n+1){clear:both}label.right{text-align:left}input[type="text"].one,.row input[type="text"].one,input[type="password"].one,.row input[type="password"].one,input[type="date"].one,.row input[type="date"].one,input[type="datetime"].one,.row input[type="datetime"].one,input[type="email"].one,.row input[type="email"].one,input[type="number"].one,.row input[type="number"].one,input[type="search"].one,.row input[type="search"].one,input[type="tel"].one,.row input[type="tel"].one,input[type="time"].one,.row input[type="time"].one,input[type="url"].one,.row input[type="url"].one,textarea.one,.row textarea.one{width:100% !important}input[type="text"].two,.row input[type="text"].two,input[type="password"].two,.row input[type="password"].two,input[type="date"].two,.row input[type="date"].two,input[type="datetime"].two,.row input[type="datetime"].two,input[type="email"].two,.row input[type="email"].two,input[type="number"].two,.row input[type="number"].two,input[type="search"].two,.row input[type="search"].two,input[type="tel"].two,.row input[type="tel"].two,input[type="time"].two,.row input[type="time"].two,input[type="url"].two,.row input[type="url"].two,textarea.two,.row textarea.two{width:100% !important}input[type="text"].three,.row input[type="text"].three,input[type="password"].three,.row input[type="password"].three,input[type="date"].three,.row input[type="date"].three,input[type="datetime"].three,.row input[type="datetime"].three,input[type="email"].three,.row input[type="email"].three,input[type="number"].three,.row input[type="number"].three,input[type="search"].three,.row input[type="search"].three,input[type="tel"].three,.row input[type="tel"].three,input[type="time"].three,.row input[type="time"].three,input[type="url"].three,.row input[type="url"].three,textarea.three,.row textarea.three{width:100% !important}input[type="text"].four,.row input[type="text"].four,input[type="password"].four,.row input[type="password"].four,input[type="date"].four,.row input[type="date"].four,input[type="datetime"].four,.row input[type="datetime"].four,input[type="email"].four,.row input[type="email"].four,input[type="number"].four,.row input[type="number"].four,input[type="search"].four,.row input[type="search"].four,input[type="tel"].four,.row input[type="tel"].four,input[type="time"].four,.row input[type="time"].four,input[type="url"].four,.row input[type="url"].four,textarea.four,.row textarea.four{width:100% !important}input[type="text"].five,.row input[type="text"].five,input[type="password"].five,.row input[type="password"].five,input[type="date"].five,.row input[type="date"].five,input[type="datetime"].five,.row input[type="datetime"].five,input[type="email"].five,.row input[type="email"].five,input[type="number"].five,.row input[type="number"].five,input[type="search"].five,.row input[type="search"].five,input[type="tel"].five,.row input[type="tel"].five,input[type="time"].five,.row input[type="time"].five,input[type="url"].five,.row input[type="url"].five,textarea.five,.row textarea.five{width:100% !important}input[type="text"].six,.row input[type="text"].six,input[type="password"].six,.row input[type="password"].six,input[type="date"].six,.row input[type="date"].six,input[type="datetime"].six,.row input[type="datetime"].six,input[type="email"].six,.row input[type="email"].six,input[type="number"].six,.row input[type="number"].six,input[type="search"].six,.row input[type="search"].six,input[type="tel"].six,.row input[type="tel"].six,input[type="time"].six,.row input[type="time"].six,input[type="url"].six,.row input[type="url"].six,textarea.six,.row textarea.six{width:100% !important}input[type="text"].seven,.row input[type="text"].seven,input[type="password"].seven,.row input[type="password"].seven,input[type="date"].seven,.row input[type="date"].seven,input[type="datetime"].seven,.row input[type="datetime"].seven,input[type="email"].seven,.row input[type="email"].seven,input[type="number"].seven,.row input[type="number"].seven,input[type="search"].seven,.row input[type="search"].seven,input[type="tel"].seven,.row input[type="tel"].seven,input[type="time"].seven,.row input[type="time"].seven,input[type="url"].seven,.row input[type="url"].seven,textarea.seven,.row textarea.seven{width:100% !important}input[type="text"].eight,.row input[type="text"].eight,input[type="password"].eight,.row input[type="password"].eight,input[type="date"].eight,.row input[type="date"].eight,input[type="datetime"].eight,.row input[type="datetime"].eight,input[type="email"].eight,.row input[type="email"].eight,input[type="number"].eight,.row input[type="number"].eight,input[type="search"].eight,.row input[type="search"].eight,input[type="tel"].eight,.row input[type="tel"].eight,input[type="time"].eight,.row input[type="time"].eight,input[type="url"].eight,.row input[type="url"].eight,textarea.eight,.row textarea.eight{width:100% !important}input[type="text"].nine,.row input[type="text"].nine,input[type="password"].nine,.row input[type="password"].nine,input[type="date"].nine,.row input[type="date"].nine,input[type="datetime"].nine,.row input[type="datetime"].nine,input[type="email"].nine,.row input[type="email"].nine,input[type="number"].nine,.row input[type="number"].nine,input[type="search"].nine,.row input[type="search"].nine,input[type="tel"].nine,.row input[type="tel"].nine,input[type="time"].nine,.row input[type="time"].nine,input[type="url"].nine,.row input[type="url"].nine,textarea.nine,.row textarea.nine{width:100% !important}input[type="text"].ten,.row input[type="text"].ten,input[type="password"].ten,.row input[type="password"].ten,input[type="date"].ten,.row input[type="date"].ten,input[type="datetime"].ten,.row input[type="datetime"].ten,input[type="email"].ten,.row input[type="email"].ten,input[type="number"].ten,.row input[type="number"].ten,input[type="search"].ten,.row input[type="search"].ten,input[type="tel"].ten,.row input[type="tel"].ten,input[type="time"].ten,.row input[type="time"].ten,input[type="url"].ten,.row input[type="url"].ten,textarea.ten,.row textarea.ten{width:100% !important}input[type="text"].eleven,.row input[type="text"].eleven,input[type="password"].eleven,.row input[type="password"].eleven,input[type="date"].eleven,.row input[type="date"].eleven,input[type="datetime"].eleven,.row input[type="datetime"].eleven,input[type="email"].eleven,.row input[type="email"].eleven,input[type="number"].eleven,.row input[type="number"].eleven,input[type="search"].eleven,.row input[type="search"].eleven,input[type="tel"].eleven,.row input[type="tel"].eleven,input[type="time"].eleven,.row input[type="time"].eleven,input[type="url"].eleven,.row input[type="url"].eleven,textarea.eleven,.row textarea.eleven{width:100% !important}input[type="text"].twelve,.row input[type="text"].twelve,input[type="password"].twelve,.row input[type="password"].twelve,input[type="date"].twelve,.row input[type="date"].twelve,input[type="datetime"].twelve,.row input[type="datetime"].twelve,input[type="email"].twelve,.row input[type="email"].twelve,input[type="number"].twelve,.row input[type="number"].twelve,input[type="search"].twelve,.row input[type="search"].twelve,input[type="tel"].twelve,.row input[type="tel"].twelve,input[type="time"].twelve,.row input[type="time"].twelve,input[type="url"].twelve,.row input[type="url"].twelve,textarea.twelve,.row textarea.twelve{width:100% !important}.button{display:block}button.button,input[type="submit"].button,input[type="reset"].button{width:100%;padding-left:0;padding-right:0}.button-group button.button,.button-group input[type="submit"].button{width:auto;padding:10px 20px 11px}.button-group button.button.large,.button-group input[type="submit"].button.large{padding:15px 30px 16px}.button-group button.button.medium,.button-group input[type="submit"].button.medium{padding:10px 20px 11px}.button-group button.button.small,.button-group input[type="submit"].button.small{padding:7px 14px 8px}.button-group button.button.tiny,.button-group input[type="submit"].button.tiny{padding:5px 10px 6px}.button-group.even button.button,.button-group.even input[type="submit"].button{width:100%;padding-left:0;padding-right:0}.nav-bar{height:auto}.nav-bar>li{float:none;display:block;border-right:none}.nav-bar>li>a.main{text-align:left;border-top:1px solid #ddd;border-right:none}.nav-bar>li:first-child>a.main{border-top:none}.nav-bar>li.has-flyout>a.flyout-toggle{position:absolute;right:0;top:0;padding:22px;z-index:2;display:block}.nav-bar>li.has-flyout.is-touch>a.flyout-toggle span{content:"";width:0;height:0;display:block}.nav-bar>li.has-flyout>a.flyout-toggle:hover span{border-top-color:#141414}.nav-bar.vertical>li.has-flyout>.flyout{left:0}.flyout{position:relative;width:100% !important;top:auto;margin-right:-2px;border-width:1px 1px 0 1px}.flyout.right{float:none;right:auto;left:-1px}.flyout.small,.flyout.large{width:100% !important}.flyout p:last-child{margin-bottom:18px}.reveal-modal-bg{position:absolute}.reveal-modal,.reveal-modal.small,.reveal-modal.medium,.reveal-modal.large,.reveal-modal.xlarge{width:80%;top:15px;left:50%;margin-left:-40%;padding:20px;height:auto}.clearing-container{margin:0}.clearing-close{z-index:99;font-size:37px;top:0px;right:5px}.clearing-caption{position:fixed;bottom:0;left:0;padding:10px !important;line-height:1.3}.clearing-main-right,.clearing-main-left{display:none}.clearing-blackout.clearing-assembled .visible-img,.clearing-blackout.clearing-assembled .clearing-container{height:100%}.clearing-blackout.clearing-assembled ul[data-clearing]{display:none}.joyride-tip-guide{width:95% !important;left:2.5% !important;-webkit-border-radius:4px;-moz-border-radius:4px;-ms-border-radius:4px;-o-border-radius:4px;border-radius:4px}.joyride-tip-guide-wrapper{width:100%}.tabs.mobile{width:auto;margin:20px -20px 40px;border-bottom:solid 1px #ccc;height:auto;margin:20px -15px 0px -15px}.tabs.mobile dt,.tabs.mobile li,.tabs.mobile dd{float:none;height:auto}.tabs.mobile dd a,.tabs.mobile li a{font-size:15px;display:block;width:auto;height:auto;padding:18px 20px;margin:0;color:#555;line-height:1;border:none;border-left:none;border-right:none;border-top:1px solid #ccc;background:#fff}.tabs.mobile dd a.active,.tabs.mobile li a.active{border:none;background:#2ba6cb;color:#fff;margin:0;position:static;top:0;height:auto}.tabs.mobile dd:first-child a.active,.tabs.mobile li:first-child a.active{margin:0}.tabs.mobile+.tabs-content.contained{margin-left:-15px;margin-right:-15px}.tabs.mobile .section-title{padding-left:20px !important}.contained.mobile{margin-bottom:0}.contained.tabs.mobile dd a,.contained.tabs.mobile li a{padding:18px 20px}.tabs.mobile+ul.contained{margin-left:-20px;margin-right:-20px;border-width:0 0 1px 0}.tooltip{font-size:14px;line-height:1.4;padding:7px 10px 9px 10px;left:50% !important;max-width:80% !important;margin-left:-40%;font-size:110%}.tooltip>.nub,.tooltip.top>.nub,.tooltip.left>.nub,.tooltip.right>.nub{border-color:transparent transparent #000 transparent;border-color:transparent transparent rgba(0,0,0,0.85) transparent;top:-12px;left:10px}}@media only screen and (max-width: 940px){.top-bar{margin-bottom:0;overflow:hidden;height:45px;background:#222}.top-bar .js-generated{display:block}.contain-to-grid .top-bar{width:auto}.top-bar section{left:0;position:relative;width:auto;-webkit-transition:left 300ms 0;-moz-transition:left 300ms 0;-o-transition:left 300ms 0;transition:left 300ms 0}.top-bar ul{width:100%;height:100%;margin-bottom:0;display:block}.top-bar ul>li{float:none}.top-bar ul>li.active,.top-bar ul>li:hover{background:#151515}.top-bar ul>li.name{height:45px}.top-bar ul>li.name h1{line-height:1}.top-bar ul>li.name h1 a{color:#fff;display:block;line-height:45px !important;padding-left:15px;height:45px}.top-bar ul>li:hover a,.top-bar ul>li.active a{color:#fff}.top-bar ul>li a:not(.button){color:#fff}.top-bar ul>li.toggle-topbar{cursor:pointer;display:block;height:45px;position:absolute;right:0;top:0;width:50%}.top-bar ul>li.toggle-topbar a{content:"";display:block;width:0;height:0;border:solid 8px;border-color:#fff transparent transparent transparent;padding:0;position:absolute;top:50%;right:22.5px;margin-top:-4px}.top-bar ul>li.toggle-topbar:hover{background:inherit}.top-bar ul>li.toggle-topbar a{padding:0 !important}.top-bar ul>li.divider{border-bottom:solid 1px #3c3c3c;border-top:solid 1px #000;clear:both;height:1px !important;margin:8px 0 !important;width:100%}.top-bar ul>li.search{padding:0 22.5px}.top-bar ul>li.search form{width:100%}.top-bar ul>li.search form input[type=text]{width:75%}.top-bar ul>li.search form .button{top:-1px;width:25%}.top-bar ul>li.has-dropdown a{padding-right:33.75px}.top-bar ul>li.has-dropdown a:after{content:"";display:block;width:0;height:0;border:solid 5px;border-color:transparent transparent transparent rgba(255,255,255,0.5);margin-right:15px;margin-top:-4.5px;position:absolute;top:50%}.top-bar ul>li.has-dropdown:hover>.dropdown{display:block;visibility:hidden}.top-bar ul>li.has-dropdown .dropdown{visibility:hidden;z-index:0 !important}.top-bar ul>li.has-dropdown.moved{position:static}.top-bar ul>li.has-dropdown.moved>.dropdown{top:0;visibility:visible}.top-bar ul>li.has-dropdown.moved>.dropdown li label{margin-bottom:6px;padding-top:6px !important;font-size:11px}.top-bar ul>li.has-dropdown.moved>.dropdown li:not(.title){padding-bottom:0}.top-bar ul>li.has-dropdown.moved>.dropdown li:not(.title) a{padding:8px 22.5px;font-size:14px}.top-bar ul>li.has-dropdown.moved>.dropdown li a,.top-bar ul>li.has-dropdown.moved>.dropdown li label{padding:0 22.5px}.top-bar ul>li.has-dropdown.moved>.dropdown li a:hover{background:#3c3c3c;display:block}.top-bar ul>li.has-dropdown.moved>.dropdown li.divider{border-bottom:solid 1px rgba(255,255,255,0.1);margin-top:8px !important;margin-bottom:8px !important}.top-bar ul>li.has-dropdown.moved .back.title{padding-bottom:0}.top-bar ul>li.has-dropdown.moved .back.title a:before{position:absolute;top:50%;left:17.5px;margin-top:-5px;width:0;height:0;content:"";display:block;width:0;height:0;border:solid 5px;border-color:transparent #fff transparent transparent}.top-bar ul>li.has-dropdown.moved .back.title h5{margin:0;padding-left:15px;position:relative}.top-bar ul>li.has-dropdown.moved .back.title h5 a{background:transparent;padding-top:8px;padding-bottom:8px;font-size:23px;font-weight:bold}.top-bar ul>li.has-dropdown .dropdown li{background:transparent}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown .dropdown{left:100% !important;top:0;right:auto !important}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown>a{padding-right:33.75px}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown>a:after{content:"";margin-right:15px;content:"";display:block;width:0;height:0;border:solid 5px;border-color:transparent transparent transparent rgba(255,255,255,0.5);position:absolute;top:50%;margin-top:-4.5px}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown>a li a:hover{background:#3c3c3c}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown.moved{position:static}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown.moved .dropdown{top:0;visibility:visible}.top-bar ul>li.has-dropdown .dropdown li.has-dropdown:hover{display:block}.top-bar ul.left,.top-bar ul.right{float:none;width:100%}.top-bar ul.left>li,.top-bar ul.right>li{display:block;float:none;margin:0 !important}.top-bar ul.left>li.has-dropdown .dropdown,.top-bar ul.right>li.has-dropdown .dropdown{left:100% !important;top:0;right:auto !important}.top-bar section>ul li a:not(.button){padding-left:22.5px !important}.top-bar.expanded{height:100%}.top-bar.expanded ul li.toggle-topbar a{content:"";display:block;width:0;height:0;border:solid 8px;border-color:transparent transparent #ccc transparent;top:auto;bottom:50%;margin-bottom:-4px}.top-bar ul li.has-button{padding:5px 15px}.top-bar ul li .button.small{margin:0 !important;display:inline-block;width:100%}.top-bar ul>li.has-button a.button{margin:0}} diff --git a/scripts/lib/esprima-master/assets/images/autocomplete.png b/scripts/lib/esprima-master/assets/images/autocomplete.png new file mode 100755 index 0000000..36d9531 Binary files /dev/null and b/scripts/lib/esprima-master/assets/images/autocomplete.png differ diff --git a/scripts/lib/esprima-master/assets/json2.js b/scripts/lib/esprima-master/assets/json2.js new file mode 100755 index 0000000..7340e2a --- /dev/null +++ b/scripts/lib/esprima-master/assets/json2.js @@ -0,0 +1,487 @@ +/* + http://www.JSON.org/json2.js + 2011-10-19 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + See http://www.JSON.org/js.html + + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. + + + This file creates a global JSON object containing two methods: stringify + and parse. + + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. + + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. + + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. + + This method produces a JSON text from a JavaScript value. + + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the value + + For example, this would serialize Dates as ISO strings. + + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. + + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. + + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. + + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. + + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. + + Example: + + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' + + + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' + + + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); + + + This is a reference implementation. You are free to copy, modify, or + redistribute. +*/ + +/*jslint evil: true, regexp: true */ + +/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf +*/ + + +// Create a JSON object only if one does not already exist. We create the +// methods in a closure to avoid creating global variables. + +var JSON; +if (!JSON) { + JSON = {}; +} + +(function () { + 'use strict'; + + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + if (typeof Date.prototype.toJSON !== 'function') { + + Date.prototype.toJSON = function (key) { + + return isFinite(this.valueOf()) + ? this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z' + : null; + }; + + String.prototype.toJSON = + Number.prototype.toJSON = + Boolean.prototype.toJSON = function (key) { + return this.valueOf(); + }; + } + + 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 + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + + + function quote(string) { + +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' + ? c + : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + + + function str(key, holder) { + +// Produce a string from holder[key]. + + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key]; + +// If the value has a toJSON method, call it to obtain a replacement value. + + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + +// If we were called with a replacer function, then call the replacer to +// obtain a replacement value. + + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + +// What happens next depends on the value's type. + + switch (typeof value) { + case 'string': + return quote(value); + + case 'number': + +// JSON numbers must be finite. Encode non-finite numbers as null. + + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + +// If the value is a boolean or null, convert it to a string. Note: +// typeof null does not produce 'null'. The case is included here in +// the remote chance that this gets fixed someday. + + return String(value); + +// If the type is 'object', we might be dealing with an object or an array or +// null. + + case 'object': + +// Due to a specification blunder in ECMAScript, typeof null is 'object', +// so watch out for that case. + + if (!value) { + return 'null'; + } + +// Make an array to hold the partial results of stringifying this object value. + + gap += indent; + partial = []; + +// Is the value an array? + + if (Object.prototype.toString.apply(value) === '[object Array]') { + +// The value is an array. Stringify every element. Use null as a placeholder +// for non-JSON values. + + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + +// Join all of the elements together, separated with commas, and wrap them in +// brackets. + + v = partial.length === 0 + ? '[]' + : gap + ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' + : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + +// If the replacer is an array, use it to select the members to be stringified. + + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + if (typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + +// Otherwise, iterate through all of the keys in the object. + + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + +// Join all of the member texts together, separated with commas, +// and wrap them in braces. + + v = partial.length === 0 + ? '{}' + : gap + ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' + : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + +// If the JSON object does not yet have a stringify method, give it one. + + if (typeof JSON.stringify !== 'function') { + JSON.stringify = function (value, replacer, space) { + +// The stringify method takes a value and an optional replacer, and an optional +// space parameter, and returns a JSON text. The replacer can be a function +// that can replace values, or an array of strings that will select the keys. +// A default replacer method can be provided. Use of the space parameter can +// produce text that is more easily readable. + + var i; + gap = ''; + indent = ''; + +// If the space parameter is a number, make an indent string containing that +// many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + +// If the space parameter is a string, it will be used as the indent string. + + } else if (typeof space === 'string') { + indent = space; + } + +// If there is a replacer, it must be a function or an array. +// Otherwise, throw an error. + + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + +// Make a fake root object containing our value under the key of ''. +// Return the result of stringifying the value. + + return str('', {'': value}); + }; + } + + +// If the JSON object does not yet have a parse method, give it one. + + if (typeof JSON.parse !== 'function') { + JSON.parse = function (text, reviver) { + +// The parse method takes a text and an optional reviver function, and returns +// a JavaScript value if the text is a valid JSON text. + + var j; + + function walk(holder, key) { + +// The walk method is used to recursively walk the resulting structure so +// that modifications can be made. + + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + } + + +// Parsing happens in four stages. In the first stage, we replace certain +// Unicode characters with escape sequences. JavaScript handles many characters +// incorrectly, either silently deleting them, or treating them as line endings. + + text = String(text); + cx.lastIndex = 0; + if (cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + +// In the second stage, we run the text against regular expressions that look +// for non-JSON patterns. We are especially concerned with '()' and 'new' +// because they can cause invocation, and '=' because it can cause mutation. +// But just to be safe, we want to reject all unexpected forms. + +// We split the second stage into 4 regexp operations in order to work around +// crippling inefficiencies in IE's and Safari's regexp engines. First we +// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we +// replace all simple value tokens with ']' characters. Third, we delete all +// open brackets that follow a colon or comma or that begin the text. Finally, +// we look to see that the remaining characters are only whitespace or ']' or +// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. + + if (/^[\],:{}\s]*$/ + .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') + .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + +// In the third stage we use the eval function to compile the text into a +// JavaScript structure. The '{' operator is subject to a syntactic ambiguity +// in JavaScript: it can begin a block or an object literal. We wrap the text +// in parens to eliminate the ambiguity. + + j = eval('(' + text + ')'); + +// In the optional fourth stage, we recursively walk the new structure, passing +// each name/value pair to a reviver function for possible transformation. + + return typeof reviver === 'function' + ? walk({'': j}, '') + : j; + } + +// If the text is not JSON parseable, then a SyntaxError is thrown. + + throw new SyntaxError('JSON.parse'); + }; + } +}()); diff --git a/scripts/lib/esprima-master/assets/orion/built-editor.css b/scripts/lib/esprima-master/assets/orion/built-editor.css new file mode 100755 index 0000000..b418ae7 --- /dev/null +++ b/scripts/lib/esprima-master/assets/orion/built-editor.css @@ -0,0 +1,419 @@ +.textview { + background-color: white; + padding: 1px 2px; +} +.textviewContainer { + background-color: #eaeaea; + font-family: 'Lucida Sans Unicode', 'Lucida Grande', Verdana, Arial, Helvetica, Myriad, Tahoma, clean, sans-serif; + font-size: 10pt; + min-width: 50px; + min-height: 50px; +} +.textviewContent { + cursor: auto; +} +.textviewLeftRuler { + border-right: 1px solid #eaeaea; +} +.textviewRightRuler { + border-left: 1px solid #eaeaea; +} +.ruler { +} +.ruler.annotations { + width: 16px; +} +.ruler.folding { + background-color: white; + width: 14px; +} +.ruler.lines { + background-color: white; + text-align: right; +} +.ruler.overview { + width: 14px; +} +.rulerLines { + color: silver; +} +.rulerLines.even +.rulerLines.odd { +} +.annotation { +} +.annotation.error, +.annotation.warning, +.annotation.task, +.annotation.bookmark, +.annotation.breakpoint, +.annotation.collapsed, +.annotation.expanded, +.annotation.currentBracket, +.annotation.matchingBracket, +.annotation.currentLine, +.annotation.matchingSearch, +.annotation.readOccurrence, +.annotation.writeOccurrence, +.annotation.currentSearch { +} +.annotationHTML { + cursor: pointer; + width: 16px; + height: 16px; + display: inline-block; + vertical-align: middle; + background-position: center; + background-repeat: no-repeat; +} +.annotationHTML.error { + + background-image: url("data:image/gif;base64,R0lGODlhEAAQANUAAPVvcvWHiPVucvRuc+ttcfV6f91KVN5LU99PV/FZY/JhaM4oN84pONE4Rd1ATfJLWutVYPRgbdxpcsgWKMgZKs4lNfE/UvE/U+artcpdSc5uXveimslHPuBhW/eJhfV5efaCgO2CgP+/v+PExP///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAACUALAAAAAAQABAAAAZ+wJJwSCwaScgkySgkjTQZTkYzWhadnE5oE+pwqkSshwQqkzxfa4kkQXxEpA9J9EFI1KQGQQBAigYCBA14ExEWF0gXihETeA0QD3AkD5QQg0NsDnAJmwkOd5gYFSQKpXAFDBhqaxgLBwQBBAapq00YEg0UDRKqTGtKSL7Cw8JBADs="); +} +.annotationHTML.warning { + + background-image: url("data:image/gif;base64,R0lGODlhEAAQANUAAP7bc//egf/ij/7ijv/jl/7kl//mnv7lnv/uwf7CTP7DTf7DT/7IW//Na/7Na//NbP7QdP/dmbltAIJNAF03AMSAJMSCLKqASa2DS6uBSquCSrGHTq6ETbCHT7WKUrKIUcCVXL+UXMOYX8GWXsSZYMiib6+ETbOIUcOXX86uhd3Muf///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAACsALAAAAAAQABAAAAZowJVwSCwaj0ihikRSJYcoBEL0XKlGkcjImQQhJBREKFnyICoThKeE/AAW6AXgdPyUAgrLJBEo0YsbAQyDhAEdRRwDDw8OaA4NDQImRBgFEJdglxAEGEQZKQcHBqOkKRpFF6mqq1WtrUEAOw=="); +} +.annotationHTML.task { + + background-image: url("data:image/gif;base64,R0lGODlhEAAQAMQAAN7s4uTy6ICvY423c2WdP2ugR3mqWYeza2ejOl6VNVqPM1aJMURsJ2GaOnKlT8PbsbPDqGmmO1OCLk98LEhxKGWfOWKaN0t2KkJoJf///////wAAAAAAAAAAAAAAAAAAACH5BAEAABoALAAAAAAQABAAAAVmoCaOZDk+UaquDxkNcCxHJHLceI6QleD/vkCmQrIYjkiDMGAhJRzQ6NKRICkKgYJ2qVWQFktCmEBYkCSNZSbQaDckpAl5TCZMSBdtAaDXX0gUUYJRFCQMSYgGDCQQGI6PkBAmkyUhADs="); +} +.annotationHTML.bookmark { + + background-image: url("data:image/gif;base64,R0lGODlhEAAQALMAAP7//+/VNPzZS/vifeumAPrBOOSlHOSuRP///wAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAgALAAAAAAQABAAAARLEMlJq5Xn3EvIrkenfRIhCB5pmKhRdbAJAGhssuc8n6eJoAKdkOaTAIdEQeWoA1oGsiZhYAnIcqiApVPjElyUbkFSgCkn5XElLYkAADs="); +} +.annotationHTML.breakpoint { + + background-image: url("data:image/gif;base64,R0lGODlhEAAQANUAAFheoFxkoFxnpmt0pmZxpnF7rYyWwmJwpnaFs3aDrWt8rXGBrYycwmZ3mXuNs42cu77F03GIs3aJrYGVu2J5oKCuxeDj6LK/03GLrYieu3aIoIygu6m4zcLN3MTM1m6Rs2aLriRgkSZilXGXtoGcs7LD0QBLhSZikihol3ScubrO2Yaqu5q4xpO0wpm7yabF0ZO9yaXI0r3X3tHj6P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAADQALAAAAAAQABAAAAafQJpwSCwWLYZBIDAwWIw0A+FFpW6aRUPCxe1yE4ahhdCCxWSzmSwGgxGeUceKpUqhUCkVa7UK0wgkJCUjJoUmIyWBBEIEGhoeJ4YmJx6OAUIADQ0QIZIhEJoAQgEUFBUgkiAVpZdRCxIPFx8iIh8XDw4FfhYHDhgZHB0dHBkYEwdwUQoTEc3OEwp+QwYHCBMMDBMIB9JESAJLAk5Q5EVBADs="); +} +.annotationHTML.collapsed { + + width: 14px; + height: 14px; + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAWBJREFUeNpi/P//PwMlgImBQkCxASzoAp++fo+6de+Z+fXbD/Jev/nAICoiwKCpqrBBTUlqNR835zJ09YzIYfDxy7eo/cevLmXlYGNQUJAEahZieP3mHcODB08Zfv/4w+BoqR3Nz8O1DKcXzt94HPqXmZlBU1+LgZNfkMHazIOBA0hr6uswgMTP33gYijcMLlx/EMAnLs7w7sc/hg9AG0HgPZB+B8S84hJA+UcBeMPg+at3DJIMnAxZzt5wsUhnXzDdsmIVWB6vAcLCfAys3z4wzN64huEfkJ/uH8IwexOQDQymD2/fgeXxekFLRWHD51evGDhZGRi4WSFSnCwgNjB2Xr1m0AbK4zXAQkdhNdPf3wx3r91g+PruLcOqnasYvn54x3Dv2k0G5r+/GMyB8nijEQTefvoadeH6w9Cbtx8GvH//kUFQkJ9BQ1V+g76m/GphPu5lBA0YenmBYgMAAgwA34GIKjmLxOUAAAAASUVORK5CYII="); +} +.annotationHTML.expanded { + + width: 14px; + height: 14px; + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAT5JREFUeNrUksFKw0AURW+mTWw67SSEiG209U90r4jddFO34l+5U0HdZCHiFwiCOz9AlMSmGEpMOqk1TWJSFGyFbATR2dyZd+Dw3mOENE3xkyP8PYHrBT3OX7uW43ZefA6FUaw1dJPSyrmu1k8KBYOh37Od4XFZLEPXFdRrFMGIw3U9TKMYqw1tb0VjcxLy9eEF425CCIxWE5JcxSQGxCyNloG87gXhwWIHc4J767lTZQw8ShFGSZbxRyaQmZJxd3NRUJ6ffwQNEi6PzG/L2tjdmvFCgcKqKL2F2Olu43MzggDka+IjPuOFI7Sbujn2fUglYKkkzFIi+R0I/QDrGS8UqDX5QkhiOHYfE84hkhSTkGNgOyDJFCzjhYLTq+vDtrG8r1LZtB6fcHtzB+uhD5VWzLx+lvF/8JV/XfAuwADsrJbMGG4l4AAAAABJRU5ErkJggg=="); +} +.annotationHTML.multiple { + + background-image: url("data:image/gif;base64,R0lGODlhEAAQANUAAOdpa+yJiuFYXOFYXeBYXONwded8f+NwdmhwkHB4iPr7/ezx+fP2+2h4kOzy+Wh4iPr8/gCBwTaczjaXyjaYyjaXyTaYyfr8/QCMzQCMzACHxzao2jal2Dak1zag03iAgI/Ckn64fZrHmX+4fZLCianPopPCiarOoqbLlafLlbnXq7nWq6fLlMTcsoCIeJCQcIiIeKCYaJiQcO16ee16evGVlfGWlfahn/ahoPWhn/WhoPe1tP///////wAAAAAAACH5BAEAAD0ALAAAAAAQABAAAAaRwJ5wSCwaj8WYcslcDmObaDTGq1Zjzw4mk+FQIRcFTzaUeTRoj4zHaI+HL0lkLnnxFgsH7zWEWSoTFBMwVlUwQy6JMDCJjYwuQx8tk5MfOzk4OjcfkSssKCkqHzY0MzQ1nEIJJSYkJCcJAQCzAQlDDyIjISMiCQYEAgMGD0MNIMfHDQUHBc3EQgjR0tPSSNY9QQA7"); +} +.annotationHTML.overlay { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJEAQvB2JVdrAAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAAD1JREFUCNdtjkESADAEAzemf69f66HMqGlOIhYiFRFRtSQBWAY7mzx+EDTL6sSgb1jTk7Q87rxyqe37fXsAa78gLyZnRgEAAAAASUVORK5CYII="); + background-position: right bottom; + position: relative; + top: -16px; +} +.annotationHTML.currentBracket { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sLEBULCGQmEKAAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAnklEQVQ4y7VTsRHDIBATJg1HCUzAHEzFBExAzwZsRMkE9gifKhc72ODYibr/+xcnoQdugq0LAujEwmbn0UxQh4OxpjX1XgshwFqLnPM5PQTQGlprWpbl3RhJ/CSQUm7qPYLp7i8cEpRSoJT6ju0lIaVEQgiKMQ4lHHpQayVjzHWCn5jIOcc8z9dMBADvPZxz3SC1tzCI8vgWdvL+VzwB8JSj2GFTyxIAAAAASUVORK5CYII="); +} +.annotationHTML.matchingBracket { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sLEBUMAsuyb3kAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAoklEQVQ4y61TsQ3EIAw80DcI0USKGIApWIsB2IGGKbJPugxBR3VfvfRRCOSTvw7LPuPzGXgI8f0gwAsFu5rXIYMdDiEOIdnKW5YFzjnEGH+bhwA/KKVwmibu0BhRnpEZY1BrHTaVT7fQJZjnGeu63tOAJFNKVEox53yqQZfAWstt27oidgm01ve3UEqBaBjnspG89wgh3LiFgZXHt3Dh23/FGxKViehm0X85AAAAAElFTkSuQmCC"); +} +.annotationHTML.currentLine { + + background-image: url("data:image/gif;base64,R0lGODlhEAAQAMQAALxe0bNWzbdZzrlb0KpPx61RybBTy6VLxadNxZGctIeUroyYsG92hHyMqIKRq2l9nmyAoHGDonaIpStXj6q80k1aXf///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABYALAAAAAAQABAAAAVCoCWOZGmeKDql5ppOMGXBk/zOoltSNO6XrlXwxIPNYiMGq8SoLC2MaNPygEQkDYdikUg6LQcEoWAICAaA5HPNLoUAADs="); +} +.annotationHTML.matchingSearch { + + background-image: url("data:image/gif;base64,R0lGODlhEAAQANUAALClrLu1ubOpsKqdp6eapKufqMTAw7attLSrsrGnr62jq8C7v765vaebpb22vLmyuMbCxsnGycfEx8G+wcrIysTBxUltof//yf///v70jergpPvws+nWc/npqvrpqvrpq/raffffnvXVkfTVkvXUkd+9f+SiOemvV+uyXa2OX7mYZqeIXKuNX/ClO7KQYqiIXJ59Vp19VpFvTo9uTZBvTpNyUJNyUf///////wAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAADgALAAAAAAQABAAAAZ4QJxwSCwajS2aS1U6DlunzcagcuKgG4sn5HJiLZ2QiHbEbj6hEapVTKVYr3OItG5TIhVGLF0npigUEAsPAjV9Q24pEhMBCAoybEUmGRcrDgcAAzNGkxcYNzAJBQSbRJ0YqBc2DaVEHJ6pGTStRBqfGBcZILRWvThBADs="); +} +.annotationHTML.currentSearch { + + background-image: url("data:image/gif;base64,R0lGODlhEAAQANUAALClrLu1ubOpsKqdp6eapKufqMTAw7attLSrsrGnr62jq8C7v765vaebpb22vLmyuMbCxsnGycfEx8G+wcrIysTBxUltof//yf///v70jergpPvws+nWc/npqvrpqvrpq/raffffnvXVkfTVkvXUkd+9f+SiOemvV+uyXa2OX7mYZqeIXKuNX/ClO7KQYqiIXJ59Vp19VpFvTo9uTZBvTpNyUJNyUf///////wAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAADgALAAAAAAQABAAAAZ4QJxwSCwajS2aS1U6DlunzcagcuKgG4sn5HJiLZ2QiHbEbj6hEapVTKVYr3OItG5TIhVGLF0npigUEAsPAjV9Q24pEhMBCAoybEUmGRcrDgcAAzNGkxcYNzAJBQSbRJ0YqBc2DaVEHJ6pGTStRBqfGBcZILRWvThBADs="); +} +.annotationOverview { + cursor: pointer; + border-radius: 2px; + left: 2px; + width: 8px; +} +.annotationOverview.task { + background-color: lightgreen; + border: 1px solid green; +} +.annotationOverview.breakpoint { + background-color: lightblue; + border: 1px solid blue; +} +.annotationOverview.bookmark { + background-color: yellow; + border: 1px solid orange; +} +.annotationOverview.error { + background-color: lightcoral; + border: 1px solid darkred; +} +.annotationOverview.warning { + background-color: Gold; + border: 1px solid black; +} +.annotationOverview.currentBracket { + background-color: lightgray; + border: 1px solid red; +} +.annotationOverview.matchingBracket { + background-color: lightgray; + border: 1px solid red; +} +.annotationOverview.currentLine { + background-color: #EAF2FE; + border: 1px solid black; +} +.annotationOverview.matchingSearch { + background-color: #C3E1FF; + border: 1px solid black; +} +.annotationOverview.currentSearch { + background-color: #53D1FF; + border: 1px solid black; +} +.annotationOverview.readOccurrence { + background-color: lightgray; + border: 1px solid black; +} +.annotationOverview.writeOccurrence { + background-color: Gold; + border: 1px solid darkred; +} +.annotationRange { + background-repeat: repeat-x; + background-position: left bottom; +} +.annotationRange.task { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sLDhEoIrb7JmcAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAGUlEQVQI12NggIH/DGdhDCM45z/DfyiBAADgdQjGhI/4DAAAAABJRU5ErkJggg=="); +} +.annotationRange.breakpoint { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sLDhEqHTKradgAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAIklEQVQI11XJMQ0AMAzAMGMafwrFlD19+sUKIJTFo9k+B/kQ+Qr2bIVKOgAAAABJRU5ErkJggg=="); +} +.annotationRange.bookmark { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII="); +} +.annotationRange.error { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg=="); +} +.annotationRange.warning { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII="); +} +.annotationRange.currentBracket { +} +.annotationRange.matchingBracket { + outline: 1px solid red; +} +.annotationRange.currentSearch { + background-color: #53D1FF; +} +.annotationRange.matchingSearch { + background-color: #C3E1FF; +} +.annotationRange.currentSearch { + background-color: #53D1FF; +} +.annotationRange.readOccurrence { + background-color: lightgray; +} +.annotationRange.writeOccurrence { + background-color: yellow; +} +.annotationLine { +} +.annotationLine.currentLine { + background-color: #EAF2FE; +} +.tooltip .textview { + color: InfoText !important; + background-color: InfoBackground !important; + padding: 0px; +} +.textviewTooltip { + font-family: monospace; + font-size: 10pt; + background-color: InfoBackground; + color: InfoText; + padding: 2px; + border-radius: 4px; + border: 1px solid black; + z-index: 100; + position: fixed; + overflow: hidden; + white-space: pre; +} +.textviewTooltip em { + font-style: normal; + font-weight: bold; +} +.tooltip .annotationLine.currentLine { + background-color: transparent; +} +.contentassist { + display: none; + background-color: #FFFFFF; + padding: 2px; + top: 100px; + left: 100px; + border: 1px solid #CCCCCC; + z-index:10; + cursor: default; + overflow: auto; + height: 150px; + width: 200px; +} +.contentassist .selected { + background-color: #EAF2FE; +} +.token_singleline_comment { + color: green; +} +.token_multiline_comment { + color: green; +} +.token_doc_comment { + color: #00008F; +} +a.token_singleline_comment, a.token_multiline_comment, a.token_doc_comment { + text-decoration: underline; +} +.token_doc_html_markup { + color: #7F7F9F; +} +.token_doc_tag { + color: #7F9FBF; +} +.token_task_tag { + color: #7F9FBF; +} +.token_string { + color: blue; +} +.token_number { + color: blue; +} +.token_keyword { + color: darkred; + font-weight: bold; +} +.token_space { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAIAAABv85FHAAAABnRSTlMA/wAAAACkwsAdAAAAIUlEQVR4nGP4z8CAC+GUIEXuABhgkTuABEiRw2cmae4EAH05X7xDolNRAAAAAElFTkSuQmCC"); + background-repeat: no-repeat; + background-position: center center; +} +.token_tab { + + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAJCAIAAACJ2loDAAAABnRSTlMA/wD/AP83WBt9AAAAMklEQVR4nGP4TwRgoK6i52c3bz5w6zMSA6tJn28d2Lx589nnCAYu63AaSLxJRLoJPwAAeNk0aG4opfMAAAAASUVORK5CYII="); + background-repeat: no-repeat; + background-position: left center; +} +.line_caret { + background-color: #EAF2FE; +} +.comment { + color: green; +} +.comment-block-documentation { + color: #00008F; +} +.constant { + font-style: italic; + color: blue; +} +.constant-character-entity { + font-style: normal; +} +.entity { + color: #3f7f7f; +} +.entity-name-function, .entity-name-type { + font-weight: bold; +} +.invalid-illegal { + color: white; + background-color: red; +} +.invalid-deprecated { + text-decoration: line-through; +} +.invalid { + color: red; + font-weight: bold; +} +.keyword-control { + color: #7F0055; + font-weight: bold; +} +.keyword-operator { + color: #ddd; +} +.markup-heading { + font-weight: bold; +} +.markup-quote { + font-style: italic; +} +.meta-tag { + color: #3f7f7f; +} +.storage { + color: #7F0055; +} +.string { + color: blue; +} +.support { + color: #21439c; +} +.variable { + color: #0000c0; +} +.variable-parameter { + color: black; +} +.variable-language { + color: #7F0055; + font-weight: bold; +} +.entity-name-tag { + color: #3f7f7f; +} +.entity-other-attribute-name { + color: #7f007f; +} +.punctuation-definition-comment { + color: #3f5fbf; +} +.punctuation-definition-string { + color: blue; +} +.string-quoted { + color: #2a00ff; +} +.cm-meta { color: #00008F; } +.cm-keyword { font-weight: bold; color: #7F0055; } +.cm-atom { color: #21439c; } +.cm-number { color: black; } +.cm-def { color: green; } +.cm-variable { color: black; } +.cm-variable-2 { color: #004080; } +.cm-variable-3 { color: #004080; } +.cm-property { color: black; } +.cm-operator { color: #222; } +.cm-comment { color: green; } +.cm-string { color: blue; } +.cm-error { color: #ff0000; } +.cm-qualifier { color: gray; } +.cm-builtin { color: #7F0055; } +.cm-bracket { color: white; background-color: gray; } +.cm-tag { color: #3f7f7f; } +.cm-attribute { color: #7f007f; } diff --git a/scripts/lib/esprima-master/assets/orion/built-editor.min.js b/scripts/lib/esprima-master/assets/orion/built-editor.min.js new file mode 100755 index 0000000..d5ac772 --- /dev/null +++ b/scripts/lib/esprima-master/assets/orion/built-editor.min.js @@ -0,0 +1,764 @@ +/* + + Copyright (c) 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + Felipe Heidrich (IBM Corporation) - initial API and implementation + Silenio Quarti (IBM Corporation) - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + Felipe Heidrich (IBM Corporation) - initial API and implementation + Silenio Quarti (IBM Corporation) - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + Felipe Heidrich (IBM Corporation) - initial API and implementation + Silenio Quarti (IBM Corporation) - initial API and implementation + Mihai Sucan (Mozilla Foundation) - fix for Bug#334583 Bug#348471 Bug#349485 Bug#350595 Bug#360726 Bug#361180 Bug#362835 Bug#362428 Bug#362286 Bug#354270 Bug#361474 Bug#363945 Bug#366312 Bug#370584 + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + Felipe Heidrich (IBM Corporation) - initial API and implementation + Silenio Quarti (IBM Corporation) - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + Felipe Heidrich (IBM Corporation) - initial API and implementation + Silenio Quarti (IBM Corporation) - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + Felipe Heidrich (IBM Corporation) - initial API and implementation + Silenio Quarti (IBM Corporation) - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + Felipe Heidrich (IBM Corporation) - initial API and implementation + Silenio Quarti (IBM Corporation) - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + Felipe Heidrich (IBM Corporation) - initial API and implementation + Silenio Quarti (IBM Corporation) - initial API and implementation + + Copyright (c) 2009, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2011, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + IBM Corporation - initial API and implementation + + Copyright (c) 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2011, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + IBM Corporation - initial API and implementation + + Copyright (c) 2011, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + IBM Corporation - initial API and implementation + + Copyright (c) 2011, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + IBM Corporation - initial API and implementation + + Copyright (c) 2011, 2012 IBM Corporation and others. + Copyright (c) 2012 VMware, Inc. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + IBM Corporation - initial API and implementation + Andrew Eisenberg - rename to jsTemplateContentAssist.js + + Copyright (c) 2011, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2011, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + IBM Corporation - initial API and implementation + + Copyright (c) 2011, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2011, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + + Copyright (c) 2010, 2012 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: IBM Corporation - initial API and implementation + Alex Lakatos - fix for bug#369781 + + Copyright (c) 2013 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + IBM Corporation - initial API and implementation + RequireJS i18n 1.0.0 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. + Available via the MIT or new BSD license. + see: http://github.com/jrburke/requirejs for details + + Copyright (c) 2011 IBM Corporation and others. + All rights reserved. This program and the accompanying materials are made + available under the terms of the Eclipse Public License v1.0 + (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + + Contributors: + IBM Corporation - initial API and implementation +*/ +var requirejs,require,define; +(function(s){function r(c,j){var q,a,b,d,e,i,f,g,k,h=j&&j.split("/"),l=o.map,m=l&&l["*"]||{};if(c&&c.charAt(0)===".")if(j){h=h.slice(0,h.length-1);c=h.concat(c.split("/"));for(g=0;g0&&(c.splice(g-1,2),g-=2);c=c.join("/")}else c.indexOf("./")===0&&(c=c.substring(2));if((h||m)&&l){q=c.split("/");for(g=q.length;g>0;g-=1){a=q.slice(0,g).join("/");if(h)for(k=h.length;k>0;k-=1)if(b=l[h.slice(0, +k).join("/")])if(b=b[a]){d=b;e=g;break}if(d)break;!i&&m&&m[a]&&(i=m[a],f=g)}!d&&i&&(d=i,e=f);d&&(q.splice(0,e,d),c=q.join("/"))}return c}function p(c,j){return function(){return a.apply(s,q.call(arguments,0).concat([c,j]))}}function f(c){return function(j){return r(j,c)}}function h(c){return function(j){i[c]=j}}function l(u){if(j.call(g,u)){var q=g[u];delete g[u];c[u]=!0;e.apply(s,q)}if(!j.call(i,u)&&!j.call(c,u))throw Error("No "+u);return i[u]}function k(c){var j,q=c?c.indexOf("!"):-1;q>-1&&(j= +c.substring(0,q),c=c.substring(q+1,c.length));return[j,c]}function m(c){return function(){return o&&o.config&&o.config[c]||{}}}var e,a,b,d,i={},g={},o={},c={},j=Object.prototype.hasOwnProperty,q=[].slice;b=function(c,j){var q,a=k(c),b=a[0],c=a[1];b&&(b=r(b,j),q=l(b));b?c=q&&q.normalize?q.normalize(c,f(j)):r(c,j):(c=r(c,j),a=k(c),b=a[0],c=a[1],b&&(q=l(b)));return{f:b?b+"!"+c:c,n:c,pr:b,p:q}};d={require:function(c){return p(c)},exports:function(c){var j=i[c];return typeof j!=="undefined"?j:i[c]={}}, +module:function(c){return{id:c,uri:"",exports:i[c],config:m(c)}}};e=function(q,a,e,n){var B,f,t,o,k=[],m,n=n||q;if(typeof e==="function"){a=!a.length&&e.length?["require","exports","module"]:a;for(o=0;o=0;l--)h[l]||h.splice(l,1);h.length===0&&delete this._eventTypes[r];f.compact=!1}}}},isListening:function(r){return!this._eventTypes?!1:this._eventTypes[r]!==void 0},removeEventListener:function(r, +p,f){if(this._eventTypes){var h=this._eventTypes[r];if(h){for(var l=h.listeners,k=0,m=l.length;k1)this._text=[this._text.join("")];var h=f.string,l=h;!f.regex&&h&&(l=h.replace(/([\\$\^*\/+?\.\(\)|{}\[\]])/g,"\\$&"));var k=null,m;if(l){var h=f.reverse,e=f.wrap,a=f.wholeWord,b=f.caseInsensitive,d=f.start||0,i=f.end,f=f.end!==void 0,g= +"";g.indexOf("g")===-1&&(g+="g");b&&g.indexOf("i")===-1&&(g+="i");a&&(l="\\b"+l+"\\b");var o=this._text[0],c,j,q=0;f&&(o=o.substring(d,i),q=d);var u=RegExp(l,g);if(h)m=function(){var a=null;for(u.lastIndex=0;;){j=u.lastIndex;c=u.exec(o);if(j===u.lastIndex)return null;if(c){if(!(c.index1;)if(e=Math.floor((a+b)/2),k=this._lineOffsets[e],m=e+11&&(f=this.getText(this.getLineEnd(0), +this.getLineEnd(0,!0))));this._lineDelimiter=f?f:r.platformDelimiter;if(h){var l=this.getLineCount();if(l>1){for(var k=Array(l),m=0;m0;)(!f.isIE||f.isIE>=9||f.isIE<9&&q[u].specified)&&j.removeAttribute(q[u].name)}if(c){if(c.styleClass)j.className=c.styleClass;if(q=c.style)for(var a in q)q.hasOwnProperty(a)&& +(j.style[a]=q[a]);if(c=c.attributes)for(var b in c)c.hasOwnProperty(b)&&j.setAttribute(b,c[b])}}function k(c){return c instanceof Array?c.slice(0):c}function m(c,j){if(c===j)return!0;if(c&&!j||!c&&j)return!1;if(c&&c.constructor===String||j&&j.constructor===String)return!1;if(c instanceof Array||j instanceof Array){if(!(c instanceof Array&&j instanceof Array))return!1;if(c.length!==j.length)return!1;for(var q=0;qthis.end)c=this.start,this.start=this.end,this.end=c,this.caret=!this.caret},setCaret:function(c){this.end=this.start=c;this.caret=!1},getCaret:function(){return this.caret?this.start:this.end},toString:function(){return"start="+this.start+" end="+this.end+(this.caret?" caret is at start":" caret is at end")},isEmpty:function(){return this.start===this.end},equals:function(c){return this.caret===c.caret&&this.start===c.start&&this.end===c.end}};i.prototype={toString:function(){return"{l="+ +this.left+", t="+this.top+", r="+this.right+", b="+this.bottom+"}"}};g.prototype={create:function(c,j){if(!this._lineDiv){var q=this._lineDiv=this._createLine(c,j,this.lineIndex);q._line=this;return q}},_createLine:function(c,j,q){var a=this.view,b=a._model,d=b.getLine(q),n=b.getLineStart(q),e={type:"LineStyle",textView:a,lineIndex:q,lineText:d,lineStart:n};if(d.length<2E3)a.onLineStyle(e);b=j||f.createElement(c.ownerDocument,"div");if(!j||!m(j.viewStyle,e.style)){l(e.style,b,j);if(j)j._trim=null; +b.viewStyle=e.style;b.setAttribute("role","presentation")}b.lineIndex=q;q=[];this._createRanges(e.ranges,d,0,d.length,n,{tabOffset:0,ranges:q});d=" ";!a._fullSelection&&f.isIE<9&&(d="\ufeff");f.isWebkit&&(d="\u200c");q.push({text:d,style:a._metrics.largestFontStyle,ignoreChars:1});var i,t,g,o,k,d=a=0,h,w;if(j){if(t=j.modelChangedEvent)t.removedLineCount===0&&t.addedLineCount===0?(w=t.start-n,h=t.addedCharCount-t.removedCharCount):w=-1,j.modelChangedEvent=void 0;t=j.firstChild}for(n=0;n=w&&(g-=h);k=(k=t.firstChild.data)?k.length:0;if(d+k>g)break;d+=k}g=t.nextSibling;b.removeChild(t);t=g}i=this._createSpan(b,o,e,i.ignoreChars);t?b.insertBefore(i,t):b.appendChild(i);if(j)j.lineWidth=void 0}if(j)for(c=i?i.nextSibling:null;c;)g=c.nextSibling,j.removeChild(c),c=g;else c.appendChild(b);return b},_createRanges:function(c, +j,q,a,b,d){if(!(q>=a)){if(c)for(var n=0;n=a)break;var f=Math.min(b+a,e.end)-b;if(i=q)){var d=this.view._customTabSize;if(d&&d!==8)for(var n= +c.indexOf("\t",j);n!==-1&&n0){for(var e="\u00a0",i=1;ic){e=c-b;if(a._isRangeRects)d=d.createRange(),d.setStart(g,e),d.setEnd(g,e+1),e=new i(d.getBoundingClientRect());else if(f.isIE)d=d.body.createTextRange(),d.moveToElementText(n),d.collapse(),d.moveEnd("character",e+1),d.moveStart("character",e),e=new i(d.getBoundingClientRect());else{var o=g.data;n.removeChild(g);n.appendChild(d.createTextNode(o.substring(0, +e)));var k=f.createElement(d,"span");k.appendChild(d.createTextNode(o.substring(e,e+1)));n.appendChild(k);n.appendChild(d.createTextNode(o.substring(e+1)));e=new i(k.getBoundingClientRect());n.innerHTML="";n.appendChild(g);this._createdDiv||(d=a._getSelection(),(b<=d.start&&d.startb.right)b.right=e.right;if(e.bottom>b.bottom)b.bottom=e.bottom}}}a=a.nextSibling}return c!==void 0?q[c]:q},_getLineBoundingClientRect:function(c,j){var q=new i(c.getBoundingClientRect());if(!this.view._wrapMode){q.right=q.left;for(var a=c.lastChild;a&&a.ignoreChars===a.firstChild.length;)a=a.previousSibling;if(a)a=a.getBoundingClientRect(),q.right=a.right+b(c).right}j&&(a=b(c),q.left+=a.left,q.right-=a.right);return q},getLineCount:function(){return!this.view._wrapMode? +1:this.getClientRects().length},getLineIndex:function(c){if(!this.view._wrapMode)return 0;for(var j=this.getClientRects(),c=this.getBoundingClientRect(c),c=c.top+(c.bottom-c.top)/2,q=0;qi.right&&(c=i.right-1)}else c<0&&(c=0),c>b.right-b.left&&(c=b.right-b.left);var o=n.ownerDocument,g=o.defaultView||o.parentWindow,k=f.isIE?g.screen.logicalXDPI/g.screen.deviceXDPI:1,h=f.isIE?g.screen.logicalYDPI/g.screen.deviceYDPI:1,g=d,l=n.firstChild; +a:for(;l;){var m=l.firstChild,n=m.length;l.ignoreChars&&(n-=l.ignoreChars);var p,r,s;e=this._getClientRects(l,b);for(var y=0;y1;){var G=Math.floor((y+F)/2);i=F+1;e=G===n-1&&l.ignoreChars?m.length:G+1;q._isRangeRects?(o.setStart(m,i),o.setEnd(m,e)):(o.moveToElementText(l),o.move("character",i),o.moveEnd("character", +e-i));e=o.getClientRects();for(var L=!1,I=0;Ip+(s-p)/2&&g++}else{i=[];for(k=0;k"), +k===n-1?i.push(m.data.substring(k)):i.push(m.data.substring(k,k+1)),i.push("");l.innerHTML=i.join("");for(k=l.firstChild;k;){i=k.getBoundingClientRect();p=i.left-b.left;s=i.right-b.left;if(p<=c&&cp+(s-p)/2&&g++;break}g++;k=k.nextSibling}if(!this._createdDiv)l.innerHTML="",l.appendChild(m),b=q._getSelection(),(g<=b.start&&b.start0?j.getLineEnd(c):j.getLineStart(c)):j==="wordend"?this._getNextOffset_W3C(c,j,q):f.isIE?this._getNextOffset_IE(c,j,q):this._getNextOffset_W3C(c,j,q)},_getNextOffset_W3C:function(c,j,q){function a(c){return 33<=c&&c<=47||58<=c&&c<=64||91<=c&&c<=94||c===96||123<=c&&c<=126}if(j==="word"||j==="wordend"){var b=this.view._model,d=b.getLineAtOffset(c),n=b.getLine(d),e=b.getLineStart(d),d=b.getLineEnd(d),b=n.length;c-=e;var i,f;if(q>0){if(c===b)return d;i=n.charCodeAt(c); +f=a(i);q=!f&&!(i===32||i===9);for(c++;cc){n=i.body.createTextRange();c===e&&q<0?n.moveToElementText(a.previousSibling):(n.moveToElementText(a),n.collapse(),n.moveEnd("character", +c-e));e=n.text.length;n.moveEnd(j,q);n=c+n.text.length-e;break}e=b+e;a=a.nextSibling}return n},destroy:function(){var c=this._createdDiv;if(c)c.parentNode.removeChild(c),this._createdDiv=null}};o.prototype={addRuler:function(c,j){c.setView(this);var a=this._rulers;if(j!==void 0){var b,d;for(b=0,d=0;b0)){var c=this._model.getLineCount();this.redrawRulers(0,c);this.redrawLines(0,c)}},redrawRulers:function(c,j){if(!(this._redrawCount>0))for(var a=this.getRulers(),b=0;b0)&&(c===void 0&&(c=0),j===void 0&&(j=this._model.getLineCount()),c!==j)){var b=this._clientDiv;if(b){if(a)for(var d= +(a.getLocation()==="left"?this._leftDiv:this._rightDiv).firstChild.rows[0].cells,e=0;e0)){var a=this._model;c===void 0&&(c=0);j===void 0&&(j=a.getCharCount());var b=a.getLineAtOffset(c),a=a.getLineAtOffset(Math.max(c,j-1))+1;this.redrawLines(b,a)}},removeRuler:function(c){for(var j=this._rulers,a=0;aj;if(b)var e=c,c=j,j=e;e=this._model.getCharCount();c=Math.max(0,Math.min(c,e));j=Math.max(0,Math.min(j,e));this._setSelection(new d(c,j,b),a===void 0||a)},setText:function(c,j,a){var b=j===void 0&&a===void 0;j===void 0&&(j=0);a===void 0&&(a=this._model.getCharCount());this._modifyContent({text:c,start:j,end:a,_code:!0},!b);if(b)this._columnX=-1,this._setSelection(new d(0,0,!1),!0),f.isFirefox&&this._fixCaret()},setTopIndex:function(c){this._clientDiv&& +this._scrollView(0,this._getLinePixel(Math.max(0,c))-this._getScroll().y)},setTopPixel:function(c){this._clientDiv&&this._scrollView(0,Math.max(0,c)-this._getScroll().y)},showSelection:function(){return this._showCaret(!0)},update:function(c,j){this._clientDiv&&(c&&this._updateStyle(),j===void 0||j?this._update():this._queueUpdate())},_handleRootMouseDown:function(c){if(f.isFirefox&&c.which===1)this._clientDiv.contentEditable=!1,this._ignoreBlur=(this._overlayDiv||this._clientDiv).draggable=!0;var j= +this._overlayDiv||this._clientDiv;if(f.isIE<9)j=this._viewDiv;for(var a=c.target?c.target:c.srcElement;a;){if(j===a)return;a=a.parentNode}c.preventDefault&&c.preventDefault();c.stopPropagation&&c.stopPropagation();if(!this._isW3CEvents){var b=this;this._getWindow().setTimeout(function(){b._clientDiv.focus()},0)}},_handleRootMouseUp:function(c){if(f.isFirefox&&c.which===1)this._clientDiv.contentEditable=!0,(this._overlayDiv||this._clientDiv).draggable=!1,this._fixCaret(),this._ignoreBlur=!1},_handleBlur:function(){if(!this._ignoreBlur){this._hasFocus= +!1;if(f.isIE<9&&!this._getSelection().isEmpty()){var c=this._rootDiv,j=f.createElement(c.ownerDocument,"div");c.appendChild(j);c.removeChild(j)}if(this._selDiv1)if(this._selDiv1.style.background="lightgray",this._selDiv2.style.background="lightgray",this._selDiv3.style.background="lightgray",c=this._getWindow(),j=this._selDiv1.ownerDocument,c.getSelection){j=c.getSelection();for(c=j.anchorNode;c;){if(c===this._clientDiv){j.rangeCount>0&&j.removeAllRanges();break}c=c.parentNode}}else if(j.selection){this._ignoreSelect= +!1;for(c=j.selection.createRange().parentElement();c;){if(c===this._clientDiv){j.selection.empty();break}c=c.parentNode}this._ignoreSelect=!0}if(!this._ignoreFocus)this.onBlur({type:"Blur"})}},_handleContextMenu:function(c){f.isIE&&this._lastMouseButton===3&&this._updateDOMSelection();var j=!1;if(this.isListening("ContextMenu"))j=this._createMouseEvent("ContextMenu",c),j.screenX=c.screenX,j.screenY=c.screenY,this.onContextMenu(j),j=j.defaultPrevented;if(j)return c.preventDefault&&c.preventDefault(), +!1},_handleCopy:function(c){if(!this._ignoreCopy&&this._doCopy(c))return c.preventDefault&&c.preventDefault(),!1},_handleCut:function(c){if(this._doCut(c))return c.preventDefault&&c.preventDefault(),!1},_handleDataModified:function(){this._startIME()},_handleDblclick:function(c){this._lastMouseTime=c.timeStamp?c.timeStamp:(new Date).getTime();if(this._clickCount!==2)this._clickCount=2,this._handleMouse(c)},_handleDragStart:function(c){if(f.isFirefox){var j=this;this._getWindow().setTimeout(function(){j._clientDiv.contentEditable= +!0;j._clientDiv.draggable=!1;j._ignoreBlur=!1},0)}if(this.isListening("DragStart")&&this._dragOffset!==-1)this._isMouseDown=!1,this.onDragStart(this._createMouseEvent("DragStart",c)),this._dragOffset=-1;else return c.preventDefault&&c.preventDefault(),!1},_handleDrag:function(c){if(this.isListening("Drag"))this.onDrag(this._createMouseEvent("Drag",c))},_handleDragEnd:function(c){this._dropTarget=!1;this._dragOffset=-1;if(this.isListening("DragEnd"))this.onDragEnd(this._createMouseEvent("DragEnd", +c));f.isFirefox&&(this._fixCaret(),c.dataTransfer.dropEffect==="none"&&!c.dataTransfer.mozUserCancelled&&this._fixCaret())},_handleDragEnter:function(c){var j=!0;this._dropTarget=!0;this.isListening("DragEnter")&&(j=!1,this.onDragEnter(this._createMouseEvent("DragEnter",c)));if(f.isWebkit||j)return c.preventDefault&&c.preventDefault(),!1},_handleDragOver:function(c){var j=!0;this.isListening("DragOver")&&(j=!1,this.onDragOver(this._createMouseEvent("DragOver",c)));if(f.isWebkit||j){if(j)c.dataTransfer.dropEffect= +"none";c.preventDefault&&c.preventDefault();return!1}},_handleDragLeave:function(c){this._dropTarget=!1;if(this.isListening("DragLeave"))this.onDragLeave(this._createMouseEvent("DragLeave",c))},_handleDrop:function(c){this._dropTarget=!1;if(this.isListening("Drop"))this.onDrop(this._createMouseEvent("Drop",c));c.preventDefault&&c.preventDefault();return!1},_handleFocus:function(){this._hasFocus=!0;f.isIOS&&this._lastTouchOffset!==void 0?(this.setCaretOffset(this._lastTouchOffset,!0),this._lastTouchOffset= +void 0):this._updateDOMSelection();if(this._selDiv1){var c=this._highlightRGB;this._selDiv1.style.background=c;this._selDiv2.style.background=c;this._selDiv3.style.background=c}if(!this._ignoreFocus)this.onFocus({type:"Focus"})},_handleKeyDown:function(c){var j=!1;switch(c.keyCode){case 16:case 17:case 18:case 91:j=!0;break;default:this._setLinksVisible(!1)}if(c.keyCode===229){if(this._readonly)return c.preventDefault&&c.preventDefault(),!1;j=!0;f.isSafari&&f.isMac&&c.ctrlKey&&(j=!1);j&&this._startIME()}else j|| +this._commitIME();if((f.isMac||f.isLinux)&&f.isFirefox<4||f.isOpera)return this._keyDownEvent=c,!0;if(this._doAction(c))return c.preventDefault?(c.preventDefault(),c.stopPropagation()):(c.cancelBubble=!0,c.returnValue=!1,c.keyCode=0),!1},_handleKeyPress:function(c){if(f.isMac&&f.isWebkit&&(63232<=c.keyCode&&c.keyCode<=63487||c.keyCode===13||c.keyCode===8))return c.preventDefault&&c.preventDefault(),!1;if(((f.isMac||f.isLinux)&&f.isFirefox<4||f.isOpera)&&this._doAction(this._keyDownEvent))return c.preventDefault&& +c.preventDefault(),!1;var j=f.isMac?c.metaKey:c.ctrlKey;if(c.charCode!==void 0&&j)switch(c.charCode){case 99:case 118:case 120:return!0}j=!1;if(f.isMac){if(c.ctrlKey||c.metaKey)j=!0}else if(f.isFirefox){if(c.ctrlKey||c.altKey)j=!0}else c.ctrlKey^c.altKey&&(j=!0);if(!j&&(j=f.isOpera?c.which:c.charCode!==void 0?c.charCode:c.keyCode,j>31))return this._doContent(String.fromCharCode(j)),c.preventDefault&&c.preventDefault(),!1},_handleKeyUp:function(c){(f.isMac?c.metaKey:c.ctrlKey)||this._setLinksVisible(!1); +c.keyCode===13&&this._commitIME()},_handleLinkClick:function(c){if(!(f.isMac?c.metaKey:c.ctrlKey))return c.preventDefault&&c.preventDefault(),!1},_handleMouse:function(c){var j=this._getWindow(),a=!0,b=j;if(f.isIE||f.isFirefox&&!this._overlayDiv)b=this._clientDiv;if(this._overlayDiv){if(this._hasFocus)this._ignoreFocus=!0;var d=this;j.setTimeout(function(){d.focus();d._ignoreFocus=!1},0)}this._clickCount===1?(a=this._setSelectionTo(c.clientX,c.clientY,c.shiftKey,!f.isOpera&&this._hasFocus&&this.isListening("DragStart")))&& +this._setGrab(b):(this._isW3CEvents&&this._setGrab(b),this._doubleClickSelection=null,this._setSelectionTo(c.clientX,c.clientY,c.shiftKey),this._doubleClickSelection=this._getSelection());return a},_handleMouseDown:function(c){if(this._linksVisible)if((c.target||c.srcElement).tagName!=="A")this._setLinksVisible(!1);else return;this._commitIME();var j=c.which;j||(c.button===4&&(j=2),c.button===2&&(j=3),c.button===1&&(j=1));var a=j!==2&&c.timeStamp?c.timeStamp:(new Date).getTime(),b=a-this._lastMouseTime, +d=Math.abs(this._lastMouseX-c.clientX),e=Math.abs(this._lastMouseY-c.clientY),n=this._lastMouseButton===j;this._lastMouseX=c.clientX;this._lastMouseY=c.clientY;this._lastMouseTime=a;this._lastMouseButton=j;if(j===1)this._isMouseDown=!0,n&&b<=this._clickTime&&d<=this._clickDist&&e<=this._clickDist?this._clickCount++:this._clickCount=1;if(this.isListening("MouseDown")&&(a=this._createMouseEvent("MouseDown",c),this.onMouseDown(a),a.defaultPrevented)){c.preventDefault();return}if(j===1&&this._handleMouse(c)&& +(f.isIE>=9||f.isOpera||f.isChrome||f.isSafari||f.isFirefox&&!this._overlayDiv))this._hasFocus||this.focus(),c.preventDefault();f.isFirefox&&this._lastMouseButton===3&&this._updateDOMSelection()},_handleMouseOver:function(c){if(this.isListening("MouseOver"))this.onMouseOver(this._createMouseEvent("MouseOver",c))},_handleMouseOut:function(c){if(this.isListening("MouseOut"))this.onMouseOut(this._createMouseEvent("MouseOut",c))},_handleMouseMove:function(c){var j=this._isClientDiv(c);if(this.isListening("MouseMove")&& +j)this.onMouseMove(this._createMouseEvent("MouseMove",c));if(!this._dropTarget){var a=this._linksVisible||this._lastMouseMoveX!==c.clientX||this._lastMouseMoveY!==c.clientY;this._lastMouseMoveX=c.clientX;this._lastMouseMoveY=c.clientY;this._setLinksVisible(a&&!this._isMouseDown&&(f.isMac?c.metaKey:c.ctrlKey));if(!this._isW3CEvents){if(c.button===0)return this._setGrab(null),!0;if(!this._isMouseDown&&c.button===1&&(this._clickCount&1)!==0&&j)return this._clickCount=2,this._handleMouse(c,this._clickCount)}if(this._isMouseDown&& +this._dragOffset===-1){var j=c.clientX,c=c.clientY,b=this._getViewPadding(),d=this._viewDiv.getBoundingClientRect(),e=this._getClientWidth(),n=this._getClientHeight(),a=d.left+b.left,i=d.top+b.top,e=d.left+b.left+e,b=d.top+b.top+n,d=this._model,n=d.getLineAtOffset(this._getSelection().getCaret());cb&&n!==d.getLineCount()-1?this._doAutoScroll("down",j,c-b):je&&!this._wrapMode?this._doAutoScroll("right", +j-e,c):(this._endAutoScroll(),this._setSelectionTo(j,c,!0))}}},_isClientDiv:function(c){for(var j=this._overlayDiv||this._clientDiv,c=c.target?c.target:c.srcElement;c;){if(j===c)return!0;c=c.parentNode}return!1},_createMouseEvent:function(c,j){var a=this.convert({x:j.clientX,y:j.clientY},"page","document");return{type:c,event:j,clickCount:this._clickCount,x:a.x,y:a.y,preventDefault:function(){this.defaultPrevented=!0}}},_handleMouseUp:function(c){var j=c.which?c.button===0:c.button===1;if(this.isListening("MouseUp")&& +(this._isClientDiv(c)||j&&this._isMouseDown))this.onMouseUp(this._createMouseEvent("MouseUp",c));if(!this._linksVisible&&j&&this._isMouseDown){if(this._dragOffset!==-1)j=this._getSelection(),j.extend(this._dragOffset),j.collapse(),this._setSelection(j,!0,!0),this._dragOffset=-1;this._isMouseDown=!1;this._endAutoScroll();this._isW3CEvents&&this._setGrab(null);f.isFirefox&&c.preventDefault()}},_handleMouseWheel:function(c){var j=this._getLineHeight(),a=0,b=0;f.isIE||f.isOpera?b=-c.wheelDelta/40*j:f.isFirefox? +(j=f.isMac?c.detail*3:Math.max(-256,Math.min(256,c.detail))*j,c.axis===c.HORIZONTAL_AXIS?a=j:b=j):f.isMac?(b=a=40,c.wheelDeltaX%120!==0&&(a=1),c.wheelDeltaY%120!==0&&(b=1),a=-c.wheelDeltaX/a,-10)a.getRangeAt(0).deleteContents(),e=b.ownerDocument.createTextNode(c.data),a.getRangeAt(0).insertNode(e),g=this._getDOMText(b,e),n=g.text,g=g.offset,e.parentNode.removeChild(e);b.lineRemoved=!0;for(b=0;i.charCodeAt(b)===n.charCodeAt(b)&&b=g+c.data.length;)a--;a++;i=n.substring(b,a+e);b+=d;a+=d;this._modifyContent({text:i,start:b,end:a,_ignoreDOMSelection:!0},!0)}}else this._doContent(c.data);c.preventDefault()},_handleTouchStart:function(c){this._commitIME();var a=this._getWindow();if(this._touchScrollTimer)this._vScrollDiv.style.display="none",this._hScrollDiv.style.display="none",a.clearInterval(this._touchScrollTimer),this._touchScrollTimer=null;var b=c.touches;if(b.length===1){var b=b[0],d=b.clientX,e=b.clientY; +this._touchStartX=d;this._touchStartY=e;if(f.isAndroid&&(e0&&a.extend(b.getLineEnd(e-1));else{var n=!1;this._expandTab&&c.unit==="character"&&(d-i)%this._tabSize===0&&(n=!/[^ ]/.test(b.getText(i,d)));n?a.extend(d-this._tabSize):(b=this._getLine(e),a.extend(b.getNextOffset(d,c.unit,-1)),b.destroy())}}this._modifyContent({text:"", +start:a.start,end:a.end},!0);return!0},_doContent:function(c){var a=this._getSelection();this._modifyContent({text:c,start:a.start,end:a.end,_ignoreDOMSelection:!0},!0)},_doCopy:function(c){var a=this._getSelection();return!a.isEmpty()?this._setClipboardText(this._getBaseText(a.start,a.end),c):!0},_doCursorNext:function(c){if(!c.select&&this._clearSelection("next"))return!0;var a=this._model,b=this._getSelection(),d=b.getCaret(),e=a.getLineAtOffset(d);d===a.getLineEnd(e)?e+10&&b.extend(a.getLineEnd(e-1)):(a=this._getLine(e),b.extend(a.getNextOffset(d,c.unit,-1)),a.destroy());c.select||b.collapse();this._setSelection(b,!0);return!0},_doCut:function(c){var a= +this._getSelection();return!a.isEmpty()?(a=this._getBaseText(a.start,a.end),this._doContent(""),this._setClipboardText(a,c)):!0},_doDelete:function(c){var a=this._getSelection();if(a.isEmpty()){var b=this._model,d=a.getCaret(),e=b.getLineAtOffset(d);d===b.getLineEnd(e)?e+10?o=i.getClientRects(d-1).top+1:(g=e===0,g||(e--,o=this._getLineHeight(e)-1));g?c.select&&(b.extend(0),this._setSelection(b,!0,!0)):(i.lineIndex!==e&&(i.destroy(),i=this._getLine(e)),b.extend(i.getOffset(n,o)),c.select||b.collapse(),this._setSelection(b,!0,!0));this._columnX=n;i.destroy();return!0},_doPageDown:function(c){var a=this._model,b=this._getSelection(), +d=b.getCaret(),e=a.getLineAtOffset(d),i=a.getLineCount(),n=this._getScroll(),g=this._getClientHeight(),o;if(this._lineHeight){a=this._columnX;n=this._getBoundsAtOffset(d);if(a===-1||c.select&&f.isIE)a=n.left;d=this._getLineIndex(n.top+g);o=this._getLine(d);e=this._getLinePixel(d);d=o.getOffset(a,n.top+g-e);g=o.getBoundingClientRect(d);o.destroy();b.extend(d);c.select||b.collapse();this._setSelection(b,!0,!0,g.top+e-n.top);this._columnX=a;return!0}if(ec&&(d=c-g);this._setSelection(b,!0,!0,d-n.y);this._columnX=a}return!0},_doPageUp:function(c){var a=this._model,b=this._getSelection(),d=b.getCaret(),e=a.getLineAtOffset(d),i=this._getScroll(),n=this._getClientHeight(),g;if(this._lineHeight){a=this._columnX; +i=this._getBoundsAtOffset(d);if(a===-1||c.select&&f.isIE)a=i.left;d=this._getLineIndex(i.bottom-n);g=this._getLine(d);e=this._getLinePixel(d);d=g.getOffset(a,i.bottom-n-e);n=g.getBoundingClientRect(d);g.destroy();b.extend(d);c.select||b.collapse();this._setSelection(b,!0,!0,n.top+e-i.top);this._columnX=a;return!0}if(e>0){var o=this._getLineHeight(),n=Math.max(1,Math.min(e,Math.floor(n/o))),a=this._columnX;if(a===-1||c.select&&f.isIE)g=this._getLine(e),a=g.getBoundingClientRect(d).left,g.destroy(); +g=this._getLine(e-n);b.extend(g.getOffset(a,this._getLineHeight(e-n)-1));g.destroy();c.select||b.collapse();c=Math.max(0,i.y-n*o);this._setSelection(b,!0,!0,c-i.y);this._columnX=a}return!0},_doPaste:function(c){var a=this;return this._getClipboardText(c,function(c){c&&(f.isLinux&&a._lastMouseButton===2&&(new Date).getTime()-a._lastMouseTime<=a._clickTime&&a._setSelectionTo(a._lastMouseX,a._lastMouseY),a._doContent(c))})!==null},_doScroll:function(c){var a=c.type,b=this._model,d=b.getLineCount(),c= +this._getClientHeight(),e=this._getLineHeight();d*=e;var i=this._getScroll().y,n;switch(a){case "textStart":n=0;break;case "textEnd":n=d-c;break;case "pageDown":n=i+c;break;case "pageUp":n=i-c;break;case "centerLine":a=this._getSelection(),n=b.getLineAtOffset(a.start),b=(b.getLineAtOffset(a.end)-n+1)*e,n=n*e-c/2+b/2}n!==void 0&&(n=Math.min(Math.max(0,n),d-c),this._scrollView(0,n-i));return!0},_doSelectAll:function(){var c=this._model,a=this._getSelection();a.setCaret(0);a.extend(c.getCharCount()); +this._setSelection(a,!1);return!0},_doTab:function(){if(this._tabMode&&!this._readonly){var c="\t";if(this._expandTab)var a=this._model,c=this._getSelection().getCaret(),b=a.getLineAtOffset(c),a=a.getLineStart(b),c=Array(this._tabSize-(c-a)%this._tabSize+1).join(" ");this._doContent(c);return!0}},_doShiftTab:function(){return!this._tabMode||this._readonly?void 0:!0},_doTabMode:function(){this._tabMode=!this._tabMode;return!0},_doWrapMode:function(){this.setOptions({wrapMode:!this.getOptions("wrapMode")}); +return!0},_autoScroll:function(){var c=this._getSelection(),a=this.convert({x:this._autoScrollX,y:this._autoScrollY},"page","document"),b=c.getCaret(),d=this._model.getLineAtOffset(b),e;if(this._autoScrollDir==="up"||this._autoScrollDir==="down")b=this._autoScrollY/this._getLineHeight(),b=b<0?Math.floor(b):Math.ceil(b),e=d,e=Math.max(0,Math.min(this._model.getLineCount()-1,e+b));else if(this._autoScrollDir==="left"||this._autoScrollDir==="right")e=this._getLineIndex(a.y),d=this._getLine(d),a.x+=d.getBoundingClientRect(b, +!1).left,d.destroy();d=this._getLine(e);c.extend(d.getOffset(a.x,a.y-this._getLinePixel(e)));d.destroy();this._setSelection(c,!0)},_autoScrollTimer:function(){this._autoScroll();var c=this;this._autoScrollTimerID=this._getWindow().setTimeout(function(){c._autoScrollTimer()},this._AUTO_SCROLL_RATE)},_calculateLineHeightTimer:function(c){if(this._lineHeight&&!this._calculateLHTimer){var a=this._model.getLineCount(),b=0;if(c){for(var c=0,d=(new Date).getTime(),e=0;b100)break;this.redrawRulers(0,a);this._queueUpdate()}c=this._getWindow();if(b!==a){var i=this;this._calculateLHTimer=c.setTimeout(function(){i._calculateLHTimer=null;i._calculateLineHeightTimer(!0)},0)}else if(this._calculateLHTimer)c.clearTimeout(this._calculateLHTimer),this._calculateLHTimer=void 0}},_calculateLineHeight:function(c){var c=this._getLine(c),a=c.getBoundingClientRect();c.destroy();return Math.max(1, +Math.ceil(a.bottom-a.top))},_calculateMetrics:function(){var c=this._clientDiv,j=c.ownerDocument,d=f.createElement(j,"div");d.style.lineHeight="normal";var e={type:"LineStyle",textView:this,0:0,lineText:this._model.getLine(0),lineStart:0};this.onLineStyle(e);l(e.style,d);d.style.position="fixed";d.style.left="-1000px";var i=f.createElement(j,"span");i.appendChild(j.createTextNode(" "));d.appendChild(i);var g=f.createElement(j,"span");g.style.fontStyle="italic";g.appendChild(j.createTextNode(" ")); +d.appendChild(g);var n=f.createElement(j,"span");n.style.fontWeight="bold";n.appendChild(j.createTextNode(" "));d.appendChild(n);e=f.createElement(j,"span");e.style.fontWeight="bold";e.style.fontStyle="italic";e.appendChild(j.createTextNode(" "));d.appendChild(e);c.appendChild(d);var o=d.getBoundingClientRect(),i=i.getBoundingClientRect(),g=g.getBoundingClientRect(),n=n.getBoundingClientRect(),e=e.getBoundingClientRect(),i=i.bottom-i.top,g=g.bottom-g.top,n=n.bottom-n.top,k=e.bottom-e.top,t=0,e=o.bottom- +o.top<=0,o=Math.max(1,o.bottom-o.top);g>i&&(t=1);n>g&&(t=2);k>n&&(t=3);var h;if(t!==0){h={style:{}};if((t&1)!==0)h.style.fontStyle="italic";if((t&2)!==0)h.style.fontWeight="bold"}i=b(d);c.removeChild(d);g=a(this._viewDiv);d=f.createElement(j,"div");d.style.position="fixed";d.style.left="-1000px";d.style.paddingLeft=g.left+"px";d.style.paddingTop=g.top+"px";d.style.paddingRight=g.right+"px";d.style.paddingBottom=g.bottom+"px";d.style.width="100px";d.style.height="100px";n=f.createElement(j,"div"); +n.style.width="100%";n.style.height="100%";d.appendChild(n);c.appendChild(d);j=d.getBoundingClientRect();g=n.getBoundingClientRect();d.style.overflow="hidden";n.style.height="200px";n=d.clientWidth;d.style.overflow="scroll";k=d.clientWidth;c.removeChild(d);g={left:g.left-j.left,top:g.top-j.top,right:j.right-g.right,bottom:j.bottom-g.bottom};return{lineHeight:o,largestFontStyle:h,lineTrim:i,viewPadding:g,scrollWidth:n-k,invalid:e}},_checkOverlayScroll:function(){if(f.isMac){var c=this,a=this._getWindow(); +this._overlayScrollTimer&&a.clearTimeout(this._overlayScrollTimer);var b=function(){var d=c._isOverOverlayScroll();d.vertical||d.horizontal?c._overlayScrollTimer=a.setTimeout(b,200):(c._overlayScrollTimer=void 0,c._update())};this._overlayScrollTimer=a.setTimeout(b,200)}},_clearSelection:function(c){var a=this._getSelection();if(a.isEmpty())return!1;c==="next"?a.start=a.end:a.end=a.start;this._setSelection(a,!0);return!0},_commitIME:function(){if(this._imeOffset!==-1){this._scrollDiv.focus();this._clientDiv.focus(); +var c=this._model,a=c.getLineAtOffset(this._imeOffset),b=c.getLineStart(a),d=this._getDOMText(this._getLineNode(a)).text,c=c.getLine(a),b=this._imeOffset-b,c=b+d.length-c.length;b!==c&&this._doContent(d.substring(b,c));this._imeOffset=-1}},_createActions:function(){var c=r.KeyBinding,a=this._keyBindings=[];a.push({actionID:"lineUp",keyBinding:new c(38),predefined:!0});a.push({actionID:"lineDown",keyBinding:new c(40),predefined:!0});a.push({actionID:"charPrevious",keyBinding:new c(37),predefined:!0}); +a.push({actionID:"charNext",keyBinding:new c(39),predefined:!0});f.isMac?(a.push({actionID:"scrollPageUp",keyBinding:new c(33),predefined:!0}),a.push({actionID:"scrollPageDown",keyBinding:new c(34),predefined:!0}),a.push({actionID:"pageUp",keyBinding:new c(33,null,null,!0),predefined:!0}),a.push({actionID:"pageDown",keyBinding:new c(34,null,null,!0),predefined:!0}),a.push({actionID:"lineStart",keyBinding:new c(37,!0),predefined:!0}),a.push({actionID:"lineEnd",keyBinding:new c(39,!0),predefined:!0}), +a.push({actionID:"wordPrevious",keyBinding:new c(37,null,null,!0),predefined:!0}),a.push({actionID:"wordNext",keyBinding:new c(39,null,null,!0),predefined:!0}),a.push({actionID:"scrollTextStart",keyBinding:new c(36),predefined:!0}),a.push({actionID:"scrollTextEnd",keyBinding:new c(35),predefined:!0}),a.push({actionID:"textStart",keyBinding:new c(38,!0),predefined:!0}),a.push({actionID:"textEnd",keyBinding:new c(40,!0),predefined:!0}),a.push({actionID:"scrollPageUp",keyBinding:new c(38,null,null,null, +!0),predefined:!0}),a.push({actionID:"scrollPageDown",keyBinding:new c(40,null,null,null,!0),predefined:!0}),a.push({actionID:"lineStart",keyBinding:new c(37,null,null,null,!0),predefined:!0}),a.push({actionID:"lineEnd",keyBinding:new c(39,null,null,null,!0),predefined:!0}),a.push({actionID:"lineStart",keyBinding:new c(38,null,null,!0),predefined:!0}),a.push({actionID:"lineEnd",keyBinding:new c(40,null,null,!0),predefined:!0})):(a.push({actionID:"pageUp",keyBinding:new c(33),predefined:!0}),a.push({actionID:"pageDown", +keyBinding:new c(34),predefined:!0}),a.push({actionID:"lineStart",keyBinding:new c(36),predefined:!0}),a.push({actionID:"lineEnd",keyBinding:new c(35),predefined:!0}),a.push({actionID:"wordPrevious",keyBinding:new c(37,!0),predefined:!0}),a.push({actionID:"wordNext",keyBinding:new c(39,!0),predefined:!0}),a.push({actionID:"textStart",keyBinding:new c(36,!0),predefined:!0}),a.push({actionID:"textEnd",keyBinding:new c(35,!0),predefined:!0}));f.isFirefox&&f.isLinux&&(a.push({actionID:"lineUp",keyBinding:new c(38, +!0),predefined:!0}),a.push({actionID:"lineDown",keyBinding:new c(40,!0),predefined:!0}));a.push({actionID:"selectLineUp",keyBinding:new c(38,null,!0),predefined:!0});a.push({actionID:"selectLineDown",keyBinding:new c(40,null,!0),predefined:!0});a.push({actionID:"selectCharPrevious",keyBinding:new c(37,null,!0),predefined:!0});a.push({actionID:"selectCharNext",keyBinding:new c(39,null,!0),predefined:!0});a.push({actionID:"selectPageUp",keyBinding:new c(33,null,!0),predefined:!0});a.push({actionID:"selectPageDown", +keyBinding:new c(34,null,!0),predefined:!0});f.isMac?(a.push({actionID:"selectLineStart",keyBinding:new c(37,!0,!0),predefined:!0}),a.push({actionID:"selectLineEnd",keyBinding:new c(39,!0,!0),predefined:!0}),a.push({actionID:"selectWordPrevious",keyBinding:new c(37,null,!0,!0),predefined:!0}),a.push({actionID:"selectWordNext",keyBinding:new c(39,null,!0,!0),predefined:!0}),a.push({actionID:"selectTextStart",keyBinding:new c(36,null,!0),predefined:!0}),a.push({actionID:"selectTextEnd",keyBinding:new c(35, +null,!0),predefined:!0}),a.push({actionID:"selectTextStart",keyBinding:new c(38,!0,!0),predefined:!0}),a.push({actionID:"selectTextEnd",keyBinding:new c(40,!0,!0),predefined:!0}),a.push({actionID:"selectLineStart",keyBinding:new c(37,null,!0,null,!0),predefined:!0}),a.push({actionID:"selectLineEnd",keyBinding:new c(39,null,!0,null,!0),predefined:!0}),a.push({actionID:"selectLineStart",keyBinding:new c(38,null,!0,!0),predefined:!0}),a.push({actionID:"selectLineEnd",keyBinding:new c(40,null,!0,!0), +predefined:!0})):(f.isLinux&&(a.push({actionID:"selectWholeLineUp",keyBinding:new c(38,!0,!0),predefined:!0}),a.push({actionID:"selectWholeLineDown",keyBinding:new c(40,!0,!0),predefined:!0})),a.push({actionID:"selectLineStart",keyBinding:new c(36,null,!0),predefined:!0}),a.push({actionID:"selectLineEnd",keyBinding:new c(35,null,!0),predefined:!0}),a.push({actionID:"selectWordPrevious",keyBinding:new c(37,!0,!0),predefined:!0}),a.push({actionID:"selectWordNext",keyBinding:new c(39,!0,!0),predefined:!0}), +a.push({actionID:"selectTextStart",keyBinding:new c(36,!0,!0),predefined:!0}),a.push({actionID:"selectTextEnd",keyBinding:new c(35,!0,!0),predefined:!0}));a.push({actionID:"undo",keyBinding:new r.KeyBinding("z",!0),predefined:!0});f.isMac?a.push({actionID:"redo",keyBinding:new r.KeyBinding("z",!0,!0),predefined:!0}):a.push({actionID:"redo",keyBinding:new r.KeyBinding("y",!0),predefined:!0});a.push({actionID:"deletePrevious",keyBinding:new c(8),predefined:!0});a.push({actionID:"deletePrevious",keyBinding:new c(8, +null,!0),predefined:!0});a.push({actionID:"deleteNext",keyBinding:new c(46),predefined:!0});a.push({actionID:"deleteWordPrevious",keyBinding:new c(8,!0),predefined:!0});a.push({actionID:"deleteWordPrevious",keyBinding:new c(8,!0,!0),predefined:!0});a.push({actionID:"deleteWordNext",keyBinding:new c(46,!0),predefined:!0});a.push({actionID:"tab",keyBinding:new c(9),predefined:!0});a.push({actionID:"shiftTab",keyBinding:new c(9,null,!0),predefined:!0});a.push({actionID:"enter",keyBinding:new c(13),predefined:!0}); +a.push({actionID:"enter",keyBinding:new c(13,null,!0),predefined:!0});a.push({actionID:"selectAll",keyBinding:new c("a",!0),predefined:!0});a.push({actionID:"toggleTabMode",keyBinding:new c("m",!0),predefined:!0});f.isMac&&(a.push({actionID:"deleteNext",keyBinding:new c(46,null,!0),predefined:!0}),a.push({actionID:"deleteWordPrevious",keyBinding:new c(8,null,null,!0),predefined:!0}),a.push({actionID:"deleteWordNext",keyBinding:new c(46,null,null,!0),predefined:!0}));if(!f.isFirefox){var b=f.isMac&& +f.isChrome;a.push({actionID:null,keyBinding:new c("u",!b,!1,!1,b),predefined:!0});a.push({actionID:null,keyBinding:new c("i",!b,!1,!1,b),predefined:!0});a.push({actionID:null,keyBinding:new c("b",!b,!1,!1,b),predefined:!0})}f.isFirefox&&(a.push({actionID:"copy",keyBinding:new c(45,!0),predefined:!0}),a.push({actionID:"paste",keyBinding:new c(45,null,!0),predefined:!0}),a.push({actionID:"cut",keyBinding:new c(46,null,!0),predefined:!0}));f.isMac&&(a.push({actionID:"lineStart",keyBinding:new c("a", +!1,!1,!1,!0),predefined:!0}),a.push({actionID:"lineEnd",keyBinding:new c("e",!1,!1,!1,!0),predefined:!0}),a.push({actionID:"lineUp",keyBinding:new c("p",!1,!1,!1,!0),predefined:!0}),a.push({actionID:"lineDown",keyBinding:new c("n",!1,!1,!1,!0),predefined:!0}),a.push({actionID:"charPrevious",keyBinding:new c("b",!1,!1,!1,!0),predefined:!0}),a.push({actionID:"charNext",keyBinding:new c("f",!1,!1,!1,!0),predefined:!0}),a.push({actionID:"deletePrevious",keyBinding:new c("h",!1,!1,!1,!0),predefined:!0}), +a.push({actionID:"deleteNext",keyBinding:new c("d",!1,!1,!1,!0),predefined:!0}),a.push({actionID:"deleteLineEnd",keyBinding:new c("k",!1,!1,!1,!0),predefined:!0}),f.isFirefox?(a.push({actionID:"scrollPageDown",keyBinding:new c("v",!1,!1,!1,!0),predefined:!0}),a.push({actionID:"deleteLineStart",keyBinding:new c("u",!1,!1,!1,!0),predefined:!0}),a.push({actionID:"deleteWordPrevious",keyBinding:new c("w",!1,!1,!1,!0),predefined:!0})):(a.push({actionID:"pageDown",keyBinding:new c("v",!1,!1,!1,!0),predefined:!0}), +a.push({actionID:"centerLine",keyBinding:new c("l",!1,!1,!1,!0),predefined:!0}),a.push({actionID:"enterNoCursor",keyBinding:new c("o",!1,!1,!1,!0),predefined:!0})));var d=this;this._actions={lineUp:{defaultHandler:function(){return d._doLineUp({select:!1})}},lineDown:{defaultHandler:function(){return d._doLineDown({select:!1})}},lineStart:{defaultHandler:function(){return d._doHome({select:!1,ctrl:!1})}},lineEnd:{defaultHandler:function(){return d._doEnd({select:!1,ctrl:!1})}},charPrevious:{defaultHandler:function(){return d._doCursorPrevious({select:!1, +unit:"character"})}},charNext:{defaultHandler:function(){return d._doCursorNext({select:!1,unit:"character"})}},pageUp:{defaultHandler:function(){return d._doPageUp({select:!1})}},pageDown:{defaultHandler:function(){return d._doPageDown({select:!1})}},scrollPageUp:{defaultHandler:function(){return d._doScroll({type:"pageUp"})}},scrollPageDown:{defaultHandler:function(){return d._doScroll({type:"pageDown"})}},wordPrevious:{defaultHandler:function(){return d._doCursorPrevious({select:!1,unit:"word"})}}, +wordNext:{defaultHandler:function(){return d._doCursorNext({select:!1,unit:"word"})}},textStart:{defaultHandler:function(){return d._doHome({select:!1,ctrl:!0})}},textEnd:{defaultHandler:function(){return d._doEnd({select:!1,ctrl:!0})}},scrollTextStart:{defaultHandler:function(){return d._doScroll({type:"textStart"})}},scrollTextEnd:{defaultHandler:function(){return d._doScroll({type:"textEnd"})}},centerLine:{defaultHandler:function(){return d._doScroll({type:"centerLine"})}},selectLineUp:{defaultHandler:function(){return d._doLineUp({select:!0})}}, +selectLineDown:{defaultHandler:function(){return d._doLineDown({select:!0})}},selectWholeLineUp:{defaultHandler:function(){return d._doLineUp({select:!0,wholeLine:!0})}},selectWholeLineDown:{defaultHandler:function(){return d._doLineDown({select:!0,wholeLine:!0})}},selectLineStart:{defaultHandler:function(){return d._doHome({select:!0,ctrl:!1})}},selectLineEnd:{defaultHandler:function(){return d._doEnd({select:!0,ctrl:!1})}},selectCharPrevious:{defaultHandler:function(){return d._doCursorPrevious({select:!0, +unit:"character"})}},selectCharNext:{defaultHandler:function(){return d._doCursorNext({select:!0,unit:"character"})}},selectPageUp:{defaultHandler:function(){return d._doPageUp({select:!0})}},selectPageDown:{defaultHandler:function(){return d._doPageDown({select:!0})}},selectWordPrevious:{defaultHandler:function(){return d._doCursorPrevious({select:!0,unit:"word"})}},selectWordNext:{defaultHandler:function(){return d._doCursorNext({select:!0,unit:"word"})}},selectTextStart:{defaultHandler:function(){return d._doHome({select:!0, +ctrl:!0})}},selectTextEnd:{defaultHandler:function(){return d._doEnd({select:!0,ctrl:!0})}},deletePrevious:{defaultHandler:function(){return d._doBackspace({unit:"character"})}},deleteNext:{defaultHandler:function(){return d._doDelete({unit:"character"})}},deleteWordPrevious:{defaultHandler:function(){return d._doBackspace({unit:"word"})}},deleteWordNext:{defaultHandler:function(){return d._doDelete({unit:"word"})}},deleteLineStart:{defaultHandler:function(){return d._doBackspace({unit:"line"})}}, +deleteLineEnd:{defaultHandler:function(){return d._doDelete({unit:"line"})}},tab:{defaultHandler:function(){return d._doTab()}},shiftTab:{defaultHandler:function(){return d._doShiftTab()}},enter:{defaultHandler:function(){return d._doEnter()}},enterNoCursor:{defaultHandler:function(){return d._doEnter({noCursor:!0})}},selectAll:{defaultHandler:function(){return d._doSelectAll()}},copy:{defaultHandler:function(){return d._doCopy()}},cut:{defaultHandler:function(){return d._doCut()}},paste:{defaultHandler:function(){return d._doPaste()}}, +toggleWrapMode:{defaultHandler:function(){return d._doWrapMode()}},toggleTabMode:{defaultHandler:function(){return d._doTabMode()}}}},_createRuler:function(c,a){if(this._clientDiv){var b=c.getLocation()==="left"?this._leftDiv:this._rightDiv;b.style.display="block";var d=f.createElement(b.ownerDocument,"div");d._ruler=c;d.rulerChanged=!0;d.style.position="relative";var b=b.firstChild.rows[0],e=b.cells.length,b=b.insertCell(a===void 0||a<0||a>e?e:a);b.vAlign="top";b.style.verticalAlign="top";b.style.borderWidth= +"0px";b.style.margin="0px";b.style.padding="0px";b.style.outline="none";b.appendChild(d)}},_createView:function(){if(!this._clientDiv){for(var c=this._parent;c.hasChildNodes();)c.removeChild(c.lastChild);var a=c.ownerDocument,b=f.createElement(a,"div");this._rootDiv=b;b.tabIndex=-1;b.style.position="relative";b.style.overflow="hidden";b.style.width="100%";b.style.height="100%";c.style.overflow="hidden";b.setAttribute("role","application");c.appendChild(b);c=f.createElement(a,"div");c.className="textviewLeftRuler"; +this._leftDiv=c;c.tabIndex=-1;c.style.overflow="hidden";c.style.MozUserSelect="none";c.style.WebkitUserSelect="none";c.style.position="absolute";c.style.cursor="default";c.style.display="none";c.setAttribute("aria-hidden","true");var d=f.createElement(a,"table");c.appendChild(d);d.cellPadding="0px";d.cellSpacing="0px";d.border="0px";d.style.borderWidth="0px";d.style.margin="0px";d.style.padding="0px";d.style.outline="none";d.style.lineHeight="normal";d=d.insertRow(0);d.style.borderWidth="0px";d.style.margin= +"0px";d.style.padding="0px";d.style.outline="none";d.style.lineHeight="normal";b.appendChild(c);c=f.createElement(a,"div");c.className="textview";this._viewDiv=c;c.tabIndex=-1;c.style.overflow="auto";c.style.position="absolute";c.style.top="0px";c.style.bottom="0px";c.style.borderWidth="0px";c.style.margin="0px";c.style.outline="none";b.appendChild(c);var e=f.createElement(a,"div");e.className="textviewRightRuler";this._rightDiv=e;e.tabIndex=-1;e.style.display="none";e.style.overflow="hidden";e.style.MozUserSelect= +"none";e.style.WebkitUserSelect="none";e.style.position="absolute";e.style.cursor="default";e.style.right="0px";e.setAttribute("aria-hidden","true");d=f.createElement(a,"table");e.appendChild(d);d.cellPadding="0px";d.cellSpacing="0px";d.border="0px";d.style.borderWidth="0px";d.style.margin="0px";d.style.padding="0px";d.style.outline="none";d.style.lineHeight="normal";d=d.insertRow(0);d.style.borderWidth="0px";d.style.margin="0px";d.style.padding="0px";d.style.outline="none";d.style.lineHeight="normal"; +b.appendChild(e);this._scrollDiv=d=f.createElement(a,"div");d.style.margin="0px";d.style.borderWidth="0px";d.style.padding="0px";c.appendChild(d);if(f.isFirefox)this._clipboardDiv=c=f.createElement(a,"div"),c.style.position="fixed",c.style.whiteSpace="pre",c.style.left="-1000px",b.appendChild(c);if(!f.isIE&&!f.isIOS)this._clipDiv=c=f.createElement(a,"div"),c.style.position="absolute",c.style.overflow="hidden",c.style.margin="0px",c.style.borderWidth="0px",c.style.padding="0px",b.appendChild(c),this._clipScrollDiv= +d=f.createElement(a,"div"),d.style.position="absolute",d.style.height="1px",d.style.top="-1000px",c.appendChild(d);this._setFullSelection(this._fullSelection,!0);c=f.createElement(a,"div");c.className="textviewContent";this._clientDiv=c;c.style.position="absolute";c.style.borderWidth="0px";c.style.margin="0px";c.style.padding="0px";c.style.outline="none";c.style.zIndex="1";c.style.WebkitUserSelect="text";c.setAttribute("spellcheck","false");if(f.isIOS||f.isAndroid)c.style.WebkitTapHighlightColor= +"transparent";(this._clipDiv||b).appendChild(c);if(f.isIOS||f.isAndroid)this._vScrollDiv=d=f.createElement(a,"div"),d.style.position="absolute",d.style.borderWidth="1px",d.style.borderColor="white",d.style.borderStyle="solid",d.style.borderRadius="4px",d.style.backgroundColor="black",d.style.opacity="0.5",d.style.margin="0px",d.style.padding="0px",d.style.outline="none",d.style.zIndex="3",d.style.width="8px",d.style.display="none",b.appendChild(d),this._hScrollDiv=d=f.createElement(a,"div"),d.style.position= +"absolute",d.style.borderWidth="1px",d.style.borderColor="white",d.style.borderStyle="solid",d.style.borderRadius="4px",d.style.backgroundColor="black",d.style.opacity="0.5",d.style.margin="0px",d.style.padding="0px",d.style.outline="none",d.style.zIndex="3",d.style.height="8px",d.style.display="none",b.appendChild(d);if(f.isFirefox&&!c.setCapture)this._overlayDiv=d=f.createElement(a,"div"),d.style.position=c.style.position,d.style.borderWidth=c.style.borderWidth,d.style.margin=c.style.margin,d.style.padding= +c.style.padding,d.style.cursor="text",d.style.zIndex="2",(this._clipDiv||b).appendChild(d);c.contentEditable="true";c.setAttribute("role","textbox");c.setAttribute("aria-multiline","true");this._setWrapMode(this._wrapMode,!0);this._setReadOnly(this._readonly);this._setThemeClass(this._themeClass,!0);this._setTabSize(this._tabSize,!0);if(!a.getElementById("_textviewStyle")&&(b="",f.isWebkit&&this._metrics.scrollWidth>0&&(b+="\n.textviewContainer ::-webkit-scrollbar-corner {background: #eeeeee;}"), +f.isFirefox&&f.isMac&&this._highlightRGB&&this._highlightRGB!=="Highlight"&&(b+="\n.textviewContainer ::-moz-selection {background: "+this._highlightRGB+";}"),b))c=f.createElement(a,"style"),c.id="_textviewStyle",d=a.getElementsByTagName("head")[0]||a.documentElement,c.appendChild(a.createTextNode(b)),d.insertBefore(c,d.firstChild);this._hookEvents();a=this._rulers;for(b=0;bthis._getLineHeight()){var c=a.getBoundingClientRect(),b=this._clientDiv.getBoundingClientRect();c.bottom>b.bottom&&(a=this._getLinePrevious(a)|| +a)}return a.lineIndex},_getBoundsAtOffset:function(c){var a=this._getLine(this._model.getLineAtOffset(c)),c=a.getBoundingClientRect(c),b=this._getLinePixel(a.lineIndex);c.top+=b;c.bottom+=b;a.destroy();return c},_getClientHeight:function(){var c=this._getViewPadding();return Math.max(0,this._viewDiv.clientHeight-c.top-c.bottom)},_getClientWidth:function(){var c=this._getViewPadding();return Math.max(0,this._viewDiv.clientWidth-c.left-c.right)},_getClipboardText:function(c,a){var b=this._model.getLineDelimiter(), +d,i,g=this._getWindow();if(g.clipboardData)return d=[],i=g.clipboardData.getData("Text"),e(i,function(c){d.push(c)},function(){d.push(b)}),i=d.join(""),a&&a(i),i;if(f.isFirefox){this._ignoreFocus=!0;var n=this._clipboardDiv;n.innerHTML="
";n.firstChild.focus();var o=this,k=function(){var c=o._getTextFromElement(n);n.innerHTML="";d=[];e(c,function(c){d.push(c)},function(){d.push(b)});return d.join("")},t=!1;this._ignorePaste=!0;if(!f.isLinux||this._lastMouseButton!==2)try{t=
+n.ownerDocument.execCommand("paste",!1,null)}catch(h){t=n.childNodes.length>1||n.firstChild&&n.firstChild.childNodes.length>0}this._ignorePaste=!1;if(!t)return c?(g.setTimeout(function(){o.focus();(i=k())&&a&&a(i);o._ignoreFocus=!1},0),null):(this.focus(),this._ignoreFocus=!1,"");this.focus();this._ignoreFocus=!1;(i=k())&&a&&a(i);return i}return c&&c.clipboardData?(d=[],i=c.clipboardData.getData("text/plain"),e(i,function(c){d.push(c)},function(){d.push(b)}),(i=d.join(""))&&a&&a(i),i):""},_getDOMText:function(c,
+a){for(var b=c.firstChild,d="",e=0;b;){var i;if(b.ignoreChars){i=b.lastChild;for(var n=0,g=[],f=-1;i;){for(var o=i.data,k=o.length-1;k>=0;k--){var h=o.substring(k,k+1);na)for(;a=c;a--)b-=this._getLineHeight(a);return b}return this._getLineHeight()*c},_getLineIndex:function(c){var a,b=0,d=this._model.getLineCount();if(this._lineHeight){var b=this._getTopIndex(),
+e=-this._topIndexY+this._getScroll().y;if(c!==e)if(c0;)c+=this._getLineHeight(--b);else for(a=this._getLineHeight(b);c-a>=e&&bthis._getLineHeight()){var c=
+a.getBoundingClientRect(),b=this._getViewPadding(),d=this._viewDiv.getBoundingClientRect();c.top=15))(d=g.MutationObserver||g.MozMutationObserver)?(this._mutationObserver=new d(function(a){c._handleDataModified(a)}),this._mutationObserver.observe(b,{subtree:!0,characterData:!0})):a.push({target:this._clientDiv,type:"DOMCharacterDataModified",handler:function(a){return c._handleDataModified(a?a:g.event)}});this._overlayDiv&&(a.push({target:this._overlayDiv,
+type:"mousedown",handler:function(a){return c._handleMouseDown(a?a:g.event)}}),a.push({target:this._overlayDiv,type:"mouseover",handler:function(a){return c._handleMouseOver(a?a:g.event)}}),a.push({target:this._overlayDiv,type:"mouseout",handler:function(a){return c._handleMouseOut(a?a:g.event)}}),a.push({target:this._overlayDiv,type:"contextmenu",handler:function(a){return c._handleContextMenu(a?a:g.event)}}));this._isW3CEvents||a.push({target:this._clientDiv,type:"dblclick",handler:function(a){return c._handleDblclick(a?
+a:g.event)}})}d=this._leftDiv;e=this._rightDiv;f.isIE&&a.push({target:d,type:"selectstart",handler:function(){return!1}});a.push({target:d,type:f.isFirefox?"DOMMouseScroll":"mousewheel",handler:function(a){return c._handleMouseWheel(a?a:g.event)}});a.push({target:d,type:"click",handler:function(a){c._handleRulerEvent(a?a:g.event)}});a.push({target:d,type:"dblclick",handler:function(a){c._handleRulerEvent(a?a:g.event)}});a.push({target:d,type:"mousemove",handler:function(a){c._handleRulerEvent(a?a:
+g.event)}});a.push({target:d,type:"mouseover",handler:function(a){c._handleRulerEvent(a?a:g.event)}});a.push({target:d,type:"mouseout",handler:function(a){c._handleRulerEvent(a?a:g.event)}});f.isIE&&a.push({target:e,type:"selectstart",handler:function(){return!1}});a.push({target:e,type:f.isFirefox?"DOMMouseScroll":"mousewheel",handler:function(a){return c._handleMouseWheel(a?a:g.event)}});a.push({target:e,type:"click",handler:function(a){c._handleRulerEvent(a?a:g.event)}});a.push({target:e,type:"dblclick",
+handler:function(a){c._handleRulerEvent(a?a:g.event)}});a.push({target:e,type:"mousemove",handler:function(a){c._handleRulerEvent(a?a:g.event)}});a.push({target:e,type:"mouseover",handler:function(a){c._handleRulerEvent(a?a:g.event)}});a.push({target:e,type:"mouseout",handler:function(a){c._handleRulerEvent(a?a:g.event)}});for(d=0;d=9)&&typeof b.ownerDocument.createRange().getBoundingClientRect==="function";this._isW3CEvents=b.addEventListener;this._autoScrollTimerID=this._autoScrollY=this._autoScrollX=null;this._AUTO_SCROLL_RATE=50;this._mouseUpClosure=this._moseMoveClosure=this._grabControl=null;this._clickCount=this._lastMouseTime=this._lastMouseY=this._lastMouseX=0;this._clickTime=250;this._clickDist=5;this._isMouseDown=!1;this._doubleClickSelection=null;this._vScroll=this._hScroll=0;this._imeOffset=-1;
+this._createActions();this._createView()},_isOverOverlayScroll:function(){if(!f.isMac)return{};var a=this._viewDiv.getBoundingClientRect(),b=this._lastMouseMoveX,d=this._lastMouseMoveY;return{vertical:a.top<=d&&db&&(n.end>b&&n.startb+g)d.lineIndex=e+i-g,d._line.lineIndex=d.lineIndex;d=this._getLineNext(d)}if(!this._wrapMode&&b<=this._maxLineIndex&&this._maxLineIndex<=b+g)this._checkMaxLineIndex=this._maxLineIndex,this._maxLineIndex=-1,this._maxLineWidth=0;this._update()},_onModelChanging:function(a){a.type=
+"ModelChanging";this.onModelChanging(a);a.type="Changing"},_queueUpdate:function(){if(!this._updateTimer&&!this._ignoreQueueUpdate){var a=this;this._updateTimer=this._getWindow().setTimeout(function(){a._updateTimer=null;a._update()},0)}},_resetLineHeight:function(a,b){if(this._wrapMode){if(a!==void 0&&b!==void 0)for(var d=a;d0&&k.removeAllRanges();k.addRange(n);var h=this,n=function(){o&&o.parentNode===
+h._clientDiv&&h._clientDiv.removeChild(o);h._updateDOMSelection()},k=!1;this._ignoreCopy=!0;try{k=i.execCommand("copy",!1,null)}catch(l){}this._ignoreCopy=!1;if(!k&&b)return g.setTimeout(n,0),!1;n();return!0},_setDOMSelection:function(a,b,d,e){for(var i,g,n,o,k=0,h=a.firstChild,l,m,z=this._model.getLine(a.lineIndex).length;h;){l=h.firstChild;m=l.length;h.ignoreChars&&(m-=h.ignoreChars);if(k+m>b||k+m>=z){i=l;g=b-k;h.ignoreChars&&m>0&&g===m&&(g+=h.ignoreChars);break}k+=m;h=h.nextSibling}for(var k=0,
+h=d.firstChild,p=this._model.getLine(d.lineIndex).length;h;){l=h.firstChild;m=l.length;h.ignoreChars&&(m-=h.ignoreChars);if(m+k>e||k+m>=p){n=l;o=e-k;h.ignoreChars&&m>0&&o===m&&(o+=h.ignoreChars);break}k+=m;h=h.nextSibling}this._setDOMFullSelection(a,b,z,d,e,p);if(this._hasFocus)if(b=this._getWindow(),a=this._parent.ownerDocument,b.getSelection){if(b=b.getSelection(),!(b.anchorNode===i&&b.anchorOffset===g&&b.focusNode===n&&b.focusOffset===o||b.anchorNode===n&&b.anchorOffset===o&&b.focusNode===i&&b.focusOffset===
+g))a=a.createRange(),a.setStart(i,g),a.setEnd(n,o),this._ignoreSelect=!1,b.rangeCount>0&&b.removeAllRanges(),b.addRange(a),this._ignoreSelect=!0}else if(a.selection)b=a.body,a=f.createElement(a,"div"),b.appendChild(a),b.removeChild(a),a=b.createTextRange(),a.moveToElementText(i.parentNode),a.moveStart("character",g),i=b.createTextRange(),i.moveToElementText(n.parentNode),i.moveStart("character",o),a.setEndPoint("EndToStart",i),this._ignoreSelect=!1,a.select(),this._ignoreSelect=!0},_setDOMFullSelection:function(a,
+b,d,e,i){if(this._selDiv1&&(d=this._selDiv1,d.style.width="0px",d.style.height="0px",d=this._selDiv2,d.style.width="0px",d.style.height="0px",d=this._selDiv3,d.style.width="0px",d.style.height="0px",!(a===e&&b===i))){var f=this._model,n=this._getViewPadding(),o=this._clientDiv.getBoundingClientRect(),k=this._viewDiv.getBoundingClientRect(),d=k.left+n.left,h=o.right,n=k.top+n.top,l=o.bottom,k=o=0;this._clipDiv?(k=this._clipDiv.getBoundingClientRect(),o=k.left-this._clipDiv.scrollLeft):(k=this._rootDiv.getBoundingClientRect(),
+o=k.left);k=k.top;this._ignoreDOMSelection=!0;var a=(new g(this,a.lineIndex,a)).getBoundingClientRect(f.getLineStart(a.lineIndex)+b,!1),m=a.left,i=(new g(this,e.lineIndex,e)).getBoundingClientRect(f.getLineStart(e.lineIndex)+i,!1),b=i.left;this._ignoreDOMSelection=!1;var f=this._selDiv1,m=Math.min(h,Math.max(d,m)),z=Math.min(l,Math.max(n,a.top)),p=h,e=Math.min(l,Math.max(n,a.bottom));f.style.left=m-o+"px";f.style.top=z-k+"px";f.style.width=Math.max(0,p-m)+"px";f.style.height=Math.max(0,e-z)+"px";
+if(a.top===i.top)p=Math.min(b,h),f.style.width=Math.max(0,p-m)+"px";else if(a=Math.min(l,Math.max(n,i.top)),b=Math.min(h,Math.max(d,b)),n=Math.min(l,Math.max(n,i.bottom)),l=this._selDiv3,l.style.left=d-o+"px",l.style.top=a-k+"px",l.style.width=Math.max(0,b-d)+"px",l.style.height=Math.max(0,n-a)+"px",a-e>0)n=this._selDiv2,n.style.left=d-o+"px",n.style.top=e-k+"px",n.style.width=Math.max(0,h-d)+"px",n.style.height=Math.max(0,a-e)+"px"}},_setGrab:function(a){if(a!==this._grabControl)a?(a.setCapture&&
+a.setCapture(),this._grabControl=a):(this._grabControl.releaseCapture&&this._grabControl.releaseCapture(),this._grabControl=null)},_setLinksVisible:function(a){if(this._linksVisible!==a){this._linksVisible=a;if(f.isIE&&a)this._hadFocus=this._hasFocus;var b=this._clientDiv;b.contentEditable=!a;this._hadFocus&&!a&&b.focus();if(this._overlayDiv)this._overlayDiv.style.zIndex=a?"-1":"1";for(a=this._getLineNext();a;){if(a.hasLink)for(b=a.firstChild;b;){var d=b.nextSibling,e=b.viewStyle;e&&e.tagName==="A"&&
+a.replaceChild(a._line._createSpan(a,b.firstChild.data,e),b);b=d}a=this._getLineNext(a)}}},_setSelection:function(a,b,d,e){if(a){this._columnX=-1;d===void 0&&(d=!0);var i=this._selection;this._selection=a;b&&this._showCaret(!1,e);d&&this._updateDOMSelection();if(!i.equals(a))this.onSelection({type:"Selection",oldValue:{start:i.start,end:i.end},newValue:{start:a.start,end:a.end}})}},_setSelectionTo:function(a,b,d,e){var i=this._model,g=this._getSelection(),b=this.convert({x:a,y:b},"page","document"),
+a=this._getLineIndex(b.y);if(this._clickCount===1){i=this._getLine(a);a=i.getOffset(b.x,b.y-this._getLinePixel(a));i.destroy();if(e&&!d&&g.start<=a&&a=this._doubleClickSelection.start?(d=this._doubleClickSelection.start,e=i.getNextOffset(a,"wordend",1)):(d=i.getNextOffset(a,"word",-1),e=this._doubleClickSelection.end):
+(d=i.getNextOffset(a,"word",-1),e=i.getNextOffset(d,"wordend",1)),i.destroy()):this._doubleClickSelection?(e=i.getLineAtOffset(this._doubleClickSelection.start),a>=e?(d=i.getLineStart(e),e=i.getLineEnd(a)):(d=i.getLineStart(a),e=i.getLineEnd(e))):(d=i.getLineStart(a),e=i.getLineEnd(a)),g.setCaret(d),g.extend(e);this._setSelection(g,!0,!0);return!0},_setFullSelection:function(a,b){this._fullSelection=a;if(f.isWebkit)this._fullSelection=!0;var d=this._clipDiv||this._rootDiv;if(d)if(this._fullSelection){if(!this._selDiv1&&
+this._fullSelection&&!f.isIOS){var e=d.ownerDocument;this._highlightRGB=f.isWebkit?"transparent":"Highlight";var i=f.createElement(e,"div");this._selDiv1=i;i.style.position="absolute";i.style.borderWidth="0px";i.style.margin="0px";i.style.padding="0px";i.style.outline="none";i.style.background=this._highlightRGB;i.style.width="0px";i.style.height="0px";i.style.zIndex="0";d.appendChild(i);var g=f.createElement(e,"div");this._selDiv2=g;g.style.position="absolute";g.style.borderWidth="0px";g.style.margin=
+"0px";g.style.padding="0px";g.style.outline="none";g.style.background=this._highlightRGB;g.style.width="0px";g.style.height="0px";g.style.zIndex="0";d.appendChild(g);this._selDiv3=e=f.createElement(e,"div");e.style.position="absolute";e.style.borderWidth="0px";e.style.margin="0px";e.style.padding="0px";e.style.outline="none";e.style.background=this._highlightRGB;e.style.width="0px";e.style.height="0px";e.style.zIndex="0";d.appendChild(e);if(f.isFirefox&&f.isMac){d=this._getWindow().getComputedStyle(e,
+null).getPropertyValue("background-color");switch(d){case "rgb(119, 141, 168)":d="rgb(199, 208, 218)";break;case "rgb(127, 127, 127)":d="rgb(198, 198, 198)";break;case "rgb(255, 193, 31)":d="rgb(250, 236, 115)";break;case "rgb(243, 70, 72)":d="rgb(255, 176, 139)";break;case "rgb(255, 138, 34)":d="rgb(255, 209, 129)";break;case "rgb(102, 197, 71)":d="rgb(194, 249, 144)";break;case "rgb(140, 78, 184)":d="rgb(232, 184, 255)";break;default:d="rgb(180, 213, 255)"}this._highlightRGB=d;i.style.background=
+d;g.style.background=d;e.style.background=d}b||this._updateDOMSelection()}}else{if(this._selDiv1)d.removeChild(this._selDiv1),this._selDiv1=null;if(this._selDiv2)d.removeChild(this._selDiv2),this._selDiv2=null;if(this._selDiv3)d.removeChild(this._selDiv3),this._selDiv3=null}},_setReadOnly:function(a){this._readonly=a;this._clientDiv.setAttribute("aria-readonly",a?"true":"false")},_setTabSize:function(a,b){this._tabSize=a;this._customTabSize=void 0;var d=this._clientDiv;if(f.isOpera){if(d)d.style.OTabSize=
+this._tabSize+""}else if(f.isWebkit>=537.1){if(d)d.style.tabSize=this._tabSize+""}else if(f.isFirefox>=4){if(d)d.style.MozTabSize=this._tabSize+""}else if(this._tabSize!==8)this._customTabSize=this._tabSize;b||(this.redrawLines(),this._resetLineWidth())},_setThemeClass:function(a,b){this._themeClass=a;var d="textviewContainer";this._themeClass&&(d+=" "+this._themeClass);this._rootDiv.className=d;this._updateStyle(b)},_setWrapMode:function(a,b){this._wrapMode=a;var d=this._clientDiv,e=this._viewDiv;
+a?(d.style.whiteSpace="pre-wrap",d.style.wordWrap="break-word",e.style.overflowX="hidden",e.style.overflowY="scroll"):(d.style.whiteSpace="pre",d.style.wordWrap="normal",e.style.overflowX="auto",e.style.overflowY="auto");b||(this.redraw(),this._resetLineWidth());this._resetLineHeight()},_showCaret:function(a,b){if(this._clientDiv){var d=this._model,e=this._getSelection(),i=this._getScroll(),g=e.getCaret(),n=e.start,f=e.end,o=d.getLineAtOffset(f),k=Math.max(Math.max(n,d.getLineStart(o)),f-1),d=this._getClientWidth(),
+o=this._getClientHeight(),h=d/4,l=this._getBoundsAtOffset(g===n?n:k),m=l.left,p=l.right,w=l.top,r=l.bottom;a&&!e.isEmpty()&&(l=this._getBoundsAtOffset(g===f?n:k),l.top===w?g===n?p=m+Math.min(l.right-m,d):m=p-Math.min(p-l.left,d):g===n?r=w+Math.min(l.bottom-w,o):w=r-Math.min(r-l.top,o));e=0;mi.x+d&&(e=Math.max(p-i.x-d,h));g=0;wi.y+o&&(g=r-i.y-o);b&&(b>0?g>0&&(g=Math.max(g,b)):g<0&&(g=Math.min(g,b)));return e!==0||g!==0?(this._scrollView(e,g),o!==this._getClientHeight()||
+d!==this._getClientWidth()?this._showCaret():this._ensureCaretVisible=!0,!0):!1}},_startIME:function(){if(this._imeOffset===-1){var a=this._getSelection();a.isEmpty()||this._modifyContent({text:"",start:a.start,end:a.end},!0);this._imeOffset=a.start}},_unhookEvents:function(){this._model.removeEventListener("preChanging",this._modelListener.onChanging);this._model.removeEventListener("postChanged",this._modelListener.onChanged);this._modelListener=null;for(var a=0;ag.lineIndex?(n=g,d=0):(n=this._getLineNode(d),d=a.start-b.getLineStart(d));eg.lineIndex?(i=g,a=0):(i=this._getLineNode(e),a=a.end-b.getLineStart(e));this._setDOMSelection(n,d,i,a)}}},_update:function(a){if(!(this._redrawCount>0)){if(this._updateTimer)this._getWindow().clearTimeout(this._updateTimer),this._updateTimer=null,a=!1;var b=this._clientDiv;if(b){if(this._metrics.invalid)this._ignoreQueueUpdate=!0,this._updateStyle(),this._ignoreQueueUpdate=!1;var d=this._model,
+e=this._getScroll(),i=this._getViewPadding(),o=d.getLineCount(),n=this._getLineHeight(),k=this._getClientWidth();if(this._wrapMode)b.style.width=k+"px";var h,l,m,v,p=0,r=0;if(this._lineHeight){for(;re.y)break;p+=m;r++}h=r;l=Math.max(0,h-1);m=d=e.y-p;h>0&&(d+=this._getLineHeight(h-1))}else v=Math.max(0,e.y)/n,h=Math.floor(v),l=Math.max(0,h-1),d=Math.round((v-l)*n),m=Math.round((v-h)*n);this._topIndexY=m;v=this._parent;var w=v.clientWidth,s=v.clientHeight;v=this._getClientHeight();
+if(a){l=0;this._leftDiv&&(h=this._leftDiv.getBoundingClientRect(),l=h.right-h.left);h=k;for(this._wrapMode||(h=Math.max(this._maxLineWidth,h));rm)(new g(this,m)).create(y,null);else{y.firstChild&&(b.insertBefore(y,n),y=C.createDocumentFragment());if(n&&n.lineChanged)n=(new g(this,m)).create(y,n),n.lineChanged=!1;n=this._getLineNext(n)}y.firstChild&&b.insertBefore(y,n);if(f.isWebkit&&!this._wrapMode)b.style.width="0x7fffffffpx";n=this._getLineNext();m=v+d;for(C=!1;n;){l=n.lineWidth;if(l===void 0)x=n._line.getBoundingClientRect(),l=n.lineWidth=Math.ceil(x.right-x.left),this._lineHeight&&
+(this._lineHeight[n.lineIndex]=Math.ceil(x.bottom-x.top));if(this._lineHeight&&!C&&(m-=this._lineHeight[n.lineIndex],m<0))e=n.lineIndex,C=!0;if(!this._wrapMode){if(l>=this._maxLineWidth)this._maxLineWidth=l,this._maxLineIndex=n.lineIndex;if(this._checkMaxLineIndex===n.lineIndex)this._checkMaxLineIndex=-1}if(n.lineIndex===h)this._topChild=n;if(n.lineIndex===e)this._bottomChild=n;n=this._getLineNext(n)}if(this._checkMaxLineIndex!==-1&&(m=this._checkMaxLineIndex,this._checkMaxLineIndex=-1,0<=m&&m=this._maxLineWidth)this._maxLineWidth=l,this._maxLineIndex=m;n.destroy()}for(;r=9)&&this._maxLineWidth>k)p+=i.right+i.left;e.style.width=p+"px";if(this._clipScrollDiv)this._clipScrollDiv.style.width=p+"px";e=this._getScroll();p=v+i.top+i.bottom;this._updateRulerSize(this._leftDiv,p);this._updateRulerSize(this._rightDiv,p)}if(this._vScrollDiv)p=v-8,r=Math.max(15,Math.ceil(Math.min(1,p/(o+i.top+i.bottom))*p)),this._vScrollDiv.style.left=l+k-8+"px",this._vScrollDiv.style.top=Math.floor(Math.max(0,
+e.y*p/o))+"px",this._vScrollDiv.style.height=r+"px";if(!this._wrapMode&&this._hScrollDiv)p=k-8,r=Math.max(15,Math.ceil(Math.min(1,p/(this._maxLineWidth+i.left+i.right))*p)),this._hScrollDiv.style.left=l+Math.floor(Math.max(0,Math.floor(e.x*p/this._maxLineWidth)))+"px",this._hScrollDiv.style.top=v-9+"px",this._hScrollDiv.style.width=r+"px";x=e.x;m=this._clipDiv;p=this._overlayDiv;if(m){m.scrollLeft=x;r=l+i.left;n=i.top;a=k;l=v;x=0;C=-d;if(e.x===0)r-=i.left,a+=i.left,x=i.left;e.x+k===h&&(a+=i.right);
+e.y===0&&(n-=i.top,l+=i.top,C+=i.top);e.y+v===o&&(l+=i.bottom);m.style.left=r+"px";m.style.top=n+"px";i=this._isOverOverlayScroll();m.style.right=w-a-r+(this._overlayScrollTimer&&i.vertical?15:0)+"px";m.style.bottom=s-l-n+(this._overlayScrollTimer&&i.horizontal?15:0)+"px";b.style.left=x+"px";b.style.top=C+"px";b.style.width=h+"px";b.style.height=v+d+"px";if(p)p.style.left=b.style.left,p.style.top=b.style.top,p.style.width=b.style.width,p.style.height=b.style.height}else{r=x;n=d;w=x+k;s=d+v;r===0&&
+(r-=i.left);n===0&&(n-=i.top);w===h&&(w+=i.right);e.y+v===o&&(s+=i.bottom);b.style.clip="rect("+n+"px,"+w+"px,"+s+"px,"+r+"px)";b.style.left=-x+l+i.left+"px";b.style.width=(f.isWebkit?h:k+x)+"px";if(!a)b.style.top=-d+i.top+"px",b.style.height=v+d+"px";if(p&&(p.style.clip=b.style.clip,p.style.left=b.style.left,p.style.width=b.style.width,!a))p.style.top=b.style.top,p.style.height=b.style.height}this._updateDOMSelection();b=this._ensureCaretVisible;this._ensureCaretVisible=!1;v!==this._getClientHeight()&&
+(this._update(),b&&this._showCaret())}}},_updateRulerSize:function(a,b){if(a){for(var d=this._topIndexY,e=this._getLineHeight(),i=a.firstChild.rows[0].cells,g=0;gp){s=f.createElement(e,"div");if(r=k[p]){l(r.style,s);if(r.html)s.innerHTML=r.html;s.annotation=r}s.lineIndex=p;s.style.height=this._getLineHeight(p)+"px";w.appendChild(s)}else if(w.firstChild&&(o.insertBefore(w,m),w=e.createDocumentFragment()),m)m=m.nextSibling;w.firstChild&&o.insertBefore(w,m)}else{r=this._getClientHeight();p=this._model.getLineCount();m=r+g.top+g.bottom-2*this._metrics.scrollWidth;h=i*p
+1;)o.removeChild(o.lastChild),r--;k=k.getAnnotations(0,p);w=e.createDocumentFragment();for(var K in k)if(p=K>>>0,!(p<0)){s=f.createElement(e,"div");r=k[K];l(r.style,s);s.style.position="absolute";s.style.top=this._metrics.scrollWidth+i+Math.floor(p*h)+"px";if(r.html)s.innerHTML=r.html;s.annotation=r;s.lineIndex=p;w.appendChild(s)}o.appendChild(w)}else if(o._oldTrackHeight!==m)for(s=o.firstChild?o.firstChild.nextSibling:null;s;)s.style.top=this._metrics.scrollWidth+i+Math.floor(s.lineIndex*h)+"px",
+s=s.nextSibling;o._oldTrackHeight=m}o.rulerChanged=!1}},_updateStyle:function(a){if(!a&&f.isIE)this._rootDiv.style.lineHeight="normal";var b=this._metrics=this._calculateMetrics();this._rootDiv.style.lineHeight=f.isIE?b.lineHeight-(b.lineTrim.top+b.lineTrim.bottom)+"px":"normal";a||(this.redraw(),this._resetLineWidth())}};p.EventTarget.addMixin(o.prototype);return{TextView:o}});
+define("orion/editor/projectionTextModel",["orion/editor/textModel","orion/editor/eventTarget"],function(s,r){function p(f){this._model=f;this._projections=[]}p.prototype={addProjection:function(f){if(f){var h=this._model,l=this._projections;f._lineIndex=h.getLineAtOffset(f.start);f._lineCount=h.getLineAtOffset(f.end)-f._lineIndex;var k=f.text;k||(k="");f._model=typeof k==="string"?new s.TextModel(k,h.getLineDelimiter()):k;var h=this.mapOffset(f.start,!0),k=f.end-f.start,m=f._lineCount,e=f._model.getCharCount(),
+a=f._model.getLineCount()-1;this.onChanging({type:"Changing",text:f._model.getText(),start:h,removedCharCount:k,addedCharCount:e,removedLineCount:m,addedLineCount:a});var b=this._binarySearch(l,f.start);l.splice(b,0,f);this.onChanged({type:"Changed",start:h,removedCharCount:k,addedCharCount:e,removedLineCount:m,addedLineCount:a})}},getProjections:function(){return this._projections.slice(0)},getBaseModel:function(){return this._model},mapOffset:function(f,h){var l=this._projections,k=0,m,e;if(h){for(m=
+0;mf)break;if(e.end>f)return-1;k+=e._model.getCharCount()-(e.end-e.start)}return f+k}for(m=0;mf-k)break;var a=e._model.getCharCount();if(e.start+a>f-k)return-1;k+=a-(e.end-e.start)}return f-k},removeProjection:function(f){var h,l=0;for(h=0;h1;)m=Math.floor((l+k)/2),h<=f[m].start?l=m:k=m;return l},getCharCount:function(){for(var f=
+this._model.getCharCount(),h=this._projections,l=0;l=f-m)break;d=i._model.getLineCount()-1;if(i._lineIndex+d>=f-m)if(a=f-(i._lineIndex+m),af-m)break;e.push(l.getText(a,i.start));d=i._model.getLineCount()-1;if(i._lineIndex+d>f-m)return e.push(i._model.getLine(0,h)),e.join("");e.push(i._model.getText());a=i.end;m+=d-i._lineCount}k=l.getLineEnd(f-m,h);af-k)break;var b=a._model.getCharCount();if(a.start+b>f-k){l=f-(a.start+k);m+=a._model.getLineAtOffset(l);
+k+=l;break}m+=a._model.getLineCount()-1-a._lineCount;k+=b-(a.end-a.start)}return h.getLineAtOffset(f-k)+m},getLineCount:function(){for(var f=this._projections,h=this._model.getLineCount(),l=0;lf-m)break;var d=b._model.getLineCount()-
+1;if(b._lineIndex+d>f-m)return b._model.getLineEnd(f-(b._lineIndex+m),h)+b.start+e;e+=b._model.getCharCount()-(b.end-b.start);m+=d-b._lineCount}return l.getLineEnd(f-m,h)+e},getLineStart:function(f){if(f<0)return-1;for(var h=this._model,l=this._projections,k=0,m=0,e=0;e=f-k)break;var b=a._model.getLineCount()-1;if(a._lineIndex+b>=f-k)return a._model.getLineStart(f-(a._lineIndex+k))+a.start+m;m+=a._model.getCharCount()-(a.end-a.start);k+=b-a._lineCount}return h.getLineStart(f-
+k)+m},getText:function(f,h){f===void 0&&(f=0);var l=this._model,k=this._projections,m=0,e=[],a,b,d;for(a=0;af-m)break;d=b._model.getCharCount();if(b.start+d>f-m)if(h!==void 0&&b.start+d>h-m)return b._model.getText(f-(b.start+m),h-(b.start+m));else e.push(b._model.getText(f-(b.start+m))),f=b.end+m+d-(b.end-b.start);m+=d-(b.end-b.start)}var i=f-m;if(h!==void 0){for(;ah-m)break;e.push(l.getText(i,b.start));d=b._model.getCharCount();if(b.start+
+d>h-m)return e.push(b._model.getText(0,h-(b.start+m))),e.join("");e.push(b._model.getText());i=b.end;m+=d-(b.end-b.start)}e.push(l.getText(i,h-m))}else{for(;ah)break;i+=l._model.getCharCount()-(l.end-l.start)}h+=i;for(var c=d;d
+o)break;i+=l._model.getCharCount()-(l.end-l.start);g+=l._model.getLineCount()-1-l._lineCount}l=o+i;i=d;this.onChanging(h,l-h,k,m+g,e);b.splice(b,i-c);for(f=f.length-(l-h);dh-b)break;o=g._model.getCharCount();if(g.start+o>h-b)if(l!==void 0&&g.start+o>l-b){g._model.setText(f,h-(g.start+b),l-(g.start+b));return}else q=g._model.getLineCount()-1-g._model.getLineAtOffset(h-(g.start+b)),c={projection:g,start:h-(g.start+b)},h=g.end+b+o-(g.end-g.start);d+=g._model.getLineCount()-1-g._lineCount;b+=o-(g.end-g.start)}h-=b;var u=i,q=e.getLineAtOffset(h)+d-q;if(l!==void 0)for(;il-b)break;o=g._model.getCharCount();if(g.start+o>l-b){d+=g._model.getLineAtOffset(l-(g.start+b));o=l-(g.start+b);l=g.end+b;j={projection:g,end:o};break}d+=g._model.getLineCount()-1-g._lineCount;b+=o-(g.end-g.start)}else{for(;i-1&&(j=e[c]);c--){i=b[j];if(i===!0||i===1)i=l(a+j+"/"+d);var g=o,q=void 0;for(q in i)!(q in f)&&!(q in g)&&(g[q]=i[q])}k(o)})})}})})();
+define("orion/editor/i18n",{load:function(s,r,p){r.specified&&r.specified("orion/bootstrap")?r(["orion/i18n!"+s],function(f){p(f)}):p({})}});
+define("orion/editor/nls/root/messages",{multipleAnnotations:"Multiple annotations:",line:"Line: ${0}",breakpoint:"Breakpoint",bookmark:"Bookmark",task:"Task",error:"Error",warning:"Warning",matchingSearch:"Matching Search",currentSearch:"Current Search",currentLine:"Current Line",matchingBracket:"Matching Bracket",currentBracket:"Current Bracket",Comment:"Comment","Flat outline":"Flat outline",incrementalFind:"Incremental find: ${0}",incrementalFindNotFound:"Incremental find: ${0} (not found)",find:"Find...",
+undo:"Undo",redo:"Redo",cancelMode:"Cancel Current Mode",findNext:"Find Next Occurrence",findPrevious:"Find Previous Occurrence",incrementalFindKey:"Incremental Find",indentLines:"Indent Lines",unindentLines:"Unindent Lines",moveLinesUp:"Move Lines Up",moveLinesDown:"Move Lines Down",copyLinesUp:"Copy Lines Up",copyLinesDown:"Copy Lines Down",deleteLines:"Delete Lines",gotoLine:"Goto Line...",gotoLinePrompty:"Goto Line:",nextAnnotation:"Next Annotation",prevAnnotation:"Previous Annotation",expand:"Expand",
+collapse:"Collapse",expandAll:"Expand All",collapseAll:"Collapse All",lastEdit:"Last Edit Location",toggleLineComment:"Toggle Line Comment",addBlockComment:"Add Block Comment",removeBlockComment:"Remove Block Comment",linkedModeEntered:"Linked Mode entered",linkedModeExited:"Linked Mode exited",syntaxError:"Syntax Error",contentAssist:"Content Assist",lineColumn:"Line ${0} : Col ${1}"});
+define("orion/editor/nls/messages",["orion/editor/i18n!orion/editor/nls/messages","orion/editor/nls/root/messages"],function(s,r){var p={root:r},f;for(f in s)s.hasOwnProperty(f)&&typeof p[f]==="undefined"&&(p[f]=s[f]);return p});
+define("orion/editor/annotations",["i18n!orion/editor/nls/messages","orion/editor/eventTarget"],function(s,r){function p(a,b,d){this.start=a;this.end=b;this._projectionModel=d;this.html=this._expandedHTML;this.style=this._expandedStyle;this.expanded=!0}function f(){}function h(a,b){var d=a.lastIndexOf("."),d=a.substring(d+1),e={title:s[d],style:{styleClass:"annotation "+d},html:"
",overviewStyle:{styleClass:"annotationOverview "+d}};b?e.lineStyle={styleClass:"annotationLine "+ +d}:e.rangeStyle={styleClass:"annotationRange "+d};f.registerType(a,e)}function l(){}function k(a){this._annotations=[];var b=this;this._listener={onChanged:function(a){b._onChanged(a)}};this.setTextModel(a)}function m(a,b){this._view=a;this._annotationModel=b;var d=this;this._listener={onDestroy:function(a){d._onDestroy(a)},onLineStyle:function(a){d._onLineStyle(a)},onChanged:function(a){d._onAnnotationModelChanged(a)}};a.addEventListener("Destroy",this._listener.onDestroy);a.addEventListener("postLineStyle", +this._listener.onLineStyle);b.addEventListener("Changed",this._listener.onChanged)}p.prototype={_expandedHTML:"
",_expandedStyle:{styleClass:"annotation expanded"},_collapsedHTML:"",_collapsedStyle:{styleClass:"annotation collapsed"},collapse:function(){if(this.expanded){this.expanded=!1;this.html=this._collapsedHTML;this.style=this._collapsedStyle;var a=this._projectionModel,b=a.getBaseModel();this._projection= +{start:b.getLineStart(b.getLineAtOffset(this.start)+1),end:b.getLineEnd(b.getLineAtOffset(this.end),!0)};a.addProjection(this._projection)}},expand:function(){if(!this.expanded)this.expanded=!0,this.html=this._expandedHTML,this.style=this._expandedStyle,this._projectionModel.removeProjection(this._projection)}};f.ANNOTATION_ERROR="orion.annotation.error";f.ANNOTATION_WARNING="orion.annotation.warning";f.ANNOTATION_TASK="orion.annotation.task";f.ANNOTATION_BREAKPOINT="orion.annotation.breakpoint"; +f.ANNOTATION_BOOKMARK="orion.annotation.bookmark";f.ANNOTATION_FOLDING="orion.annotation.folding";f.ANNOTATION_CURRENT_BRACKET="orion.annotation.currentBracket";f.ANNOTATION_MATCHING_BRACKET="orion.annotation.matchingBracket";f.ANNOTATION_CURRENT_LINE="orion.annotation.currentLine";f.ANNOTATION_CURRENT_SEARCH="orion.annotation.currentSearch";f.ANNOTATION_MATCHING_SEARCH="orion.annotation.matchingSearch";f.ANNOTATION_READ_OCCURRENCE="orion.annotation.readOccurrence";f.ANNOTATION_WRITE_OCCURRENCE="orion.annotation.writeOccurrence"; +var e={};f.registerType=function(a,b){var d=b;if(typeof d!=="function")d=function(a,b,d){this.start=a;this.end=b;if(d)this.title=d},d.prototype=b;d.prototype.type=a;e[a]=d;return a};f.createAnnotation=function(a,b,d,e){return new (this.getType(a))(b,d,e)};f.getType=function(a){return e[a]};h(f.ANNOTATION_ERROR);h(f.ANNOTATION_WARNING);h(f.ANNOTATION_TASK);h(f.ANNOTATION_BREAKPOINT);h(f.ANNOTATION_BOOKMARK);h(f.ANNOTATION_CURRENT_BRACKET);h(f.ANNOTATION_MATCHING_BRACKET);h(f.ANNOTATION_CURRENT_SEARCH); +h(f.ANNOTATION_MATCHING_SEARCH);h(f.ANNOTATION_READ_OCCURRENCE);h(f.ANNOTATION_WRITE_OCCURRENCE);h(f.ANNOTATION_CURRENT_LINE,!0);f.registerType(f.ANNOTATION_FOLDING,p);l.addMixin=function(a){var b=l.prototype,d;for(d in b)b.hasOwnProperty(d)&&(a[d]=b[d])};l.prototype={addAnnotationType:function(a){if(!this._annotationTypes)this._annotationTypes=[];this._annotationTypes.push(a)},getAnnotationTypePriority:function(a){if(this._annotationTypes)for(var b=0;bc.start?a=b)break}return null};e=f();return{next:function(){var a=e; +a&&(e=f());return a},hasNext:function(){return e!==null}}},modifyAnnotation:function(a){if(a&&!(this._getAnnotationIndex(a)<0))this.onChanged({type:"Changed",added:[],removed:[],changed:[a]})},onChanged:function(a){return this.dispatchEvent(a)},removeAnnotations:function(a){var b=this._annotations,d,e;if(a){d=[];for(e=b.length-1;e>=0;e--){var g=b[e];g.type===a&&b.splice(e,1);d.splice(0,0,g)}}else d=b;this.onChanged({type:"Changed",removed:d,added:[],changed:[]})},removeAnnotation:function(a){if(a&& +(a=this._getAnnotationIndex(a),!(a<0)))this.onChanged({type:"Changed",removed:this._annotations.splice(a,1),added:[],changed:[]})},replaceAnnotations:function(a,b){var d=this._annotations,e,g,f,c=[];if(a)for(e=a.length-1;e>=0;e--)f=a[e],g=this._getAnnotationIndex(f),g<0||(d.splice(g,1),c.splice(0,0,f));b||(b=[]);for(e=0;e1;)g=Math.floor((d+e)/2),b<=a[g].start?d=g:e=g;return d},_getAnnotationIndex:function(a){for(var b=this._annotations,d=this._binarySearch(b,a.start);d=g?(c.start+=a,c.end+=a,f.changed.push(c)):c.end<=b||(c.start0||f.removed.length>0||f.changed.length>0)this.onChanged(f)}}};r.EventTarget.addMixin(k.prototype);m.prototype={destroy:function(){var a=this._view;if(a)a.removeEventListener("Destroy",this._listener.onDestroy),a.removeEventListener("LineStyle", +this._listener.onLineStyle),this.view=null;(a=this._annotationModel)&&a.removeEventListener("Changed",this._listener.onChanged)},_mergeStyle:function(a,b){if(b){a||(a={});a.styleClass&&b.styleClass&&a.styleClass!==b.styleClass?a.styleClass+=" "+b.styleClass:a.styleClass=b.styleClass;var d;if(b.style){if(!a.style)a.style={};for(d in b.style)a.style[d]||(a.style[d]=b.style[d])}if(b.attributes){if(!a.attributes)a.attributes={};for(d in b.attributes)a.attributes[d]||(a.attributes[d]=b.attributes[d])}}return a}, +_mergeStyleRanges:function(a,b){a||(a=[]);var d,e;for(e=0;e=g.end)){d=this._mergeStyle({},g.style);d=this._mergeStyle(d,b.style);var f=[];f.push(e,1);b.startg.start&&f.push({start:g.start,end:b.start,style:g.style});f.push({start:Math.max(g.start,b.start),end:Math.min(g.end,b.end),style:d});b.endg.end?{start:g.end, +end:b.end,style:b.style}:null;Array.prototype.splice.apply(a,f)}}b&&(d=this._mergeStyle({},b.style),a.splice(e,0,{start:b.start,end:b.end,style:d}));return a},_onAnnotationModelChanged:function(a){function b(a){for(var b=0;b0?(a-=0.1,e.style.opacity=a):o.hide()},50)},5E3)}}}},_getAnnotationContents:function(k){function h(b){var d=b.title;if(d==="")return null;var e="
";b.html&&(e+=b.html+" ");if(!d)d=b.end,b=a.getLineStart(a.getLineAtOffset(b.start)),d=a.getLineEnd(a.getLineAtOffset(d),!0),d=a.getText(b,d);d=d.replace(//g, +">");e+=""+d+"
";return e}if(k.length===0)return null;var e=this._view.getModel(),a=e.getBaseModel?e.getBaseModel():e;if(k.length===1)if(e=k[0],e.title!==void 0)return h(e);else{var k=new f.ProjectionTextModel(a),b=a.getLineStart(a.getLineAtOffset(e.start)),d=a.getCharCount();e.end!==d&&k.addProjection({start:e.end,end:d});b>0&&k.addProjection({start:0,end:b});return k}else{b="
"+s.multipleAnnotations+"
";for(d=0;d=0;l--)this.changes[l].undo(f,!1);if(h){var l=this.startSelection.start,k=this.startSelection.end;f.setSelection(this.startCaret?l:k,this.startCaret?k:l)}},redo:function(f,h){for(var l=0;lthis.size&&(this.stack.shift(),this.index--,this.cleanIndex--))},markClean:function(){this.endCompoundChange();this._commitUndo();this.cleanIndex=this.index},isClean:function(){return this.cleanIndex=== +this.getSize().undo},canUndo:function(){return this.getSize().undo>0},canRedo:function(){return this.getSize().redo>0},endCompoundChange:function(){this.compoundChange&&this.compoundChange.end(this.view);this.compoundChange=void 0},getSize:function(){var f=this.index,h=this.stack.length;this._undoStart!==void 0&&f++;return{undo:f,redo:h-f}},undo:function(){this._commitUndo();if(this.index<=0)return!1;var f=this.stack[--this.index];this._ignoreUndo=!0;f.undo(this.view,!0);this._ignoreUndo=!1;return!0}, +redo:function(){this._commitUndo();if(this.index>=this.stack.length)return!1;var f=this.stack[this.index++];this._ignoreUndo=!0;f.redo(this.view,!0);this._ignoreUndo=!1;return!0},reset:function(){this.index=this.cleanIndex=0;this.stack=[];this._undoStart=void 0;this._undoText="";this._undoType=0;this._ignoreUndo=!1;this._compoundChange=void 0},startCompoundChange:function(){this._commitUndo();var f=new r;this.add(f);this.compoundChange=f;this.compoundChange.start(this.view)},_commitUndo:function(){if(this._undoStart!== +void 0)this._undoType===-1?this.add(new s(this._undoStart,"",this._undoText)):this.add(new s(this._undoStart,this._undoText,"")),this._undoStart=void 0,this._undoText="",this._undoType=0},_onDestroy:function(){this.model.removeEventListener("Changing",this._listener.onChanging);this.view.removeEventListener("Destroy",this._listener.onDestroy)},_onChanging:function(f){var h=f.text,l=f.start,k=f.removedCharCount,f=f.addedCharCount;if(!this._ignoreUndo){this._undoStart!==void 0&&!(f===1&&k===0&&this._undoType=== +1&&l===this._undoStart+this._undoText.length||f===0&&k===1&&this._undoType===-1&&(l+1===this._undoStart||l===this._undoStart))&&this._commitUndo();if(!this.compoundChange)if(f===1&&k===0){if(this._undoStart===void 0)this._undoStart=l;this._undoText+=h;this._undoType=1;return}else if(f===0&&k===1){h=this._undoText.length>0&&this._undoStart===l;this._undoStart=l;this._undoType=-1;h?this._undoText+=this.model.getText(l,l+k):this._undoText=this.model.getText(l,l+k)+this._undoText;return}this.add(new s(l, +h,this.model.getText(l,l+k)))}}};return{UndoStack:p}}); +define("orion/editor/textDND",[],function(){function s(r,p){this._view=r;this._undoStack=p;this._dragSelection=null;this._dropOffset=-1;this._dropText=null;var f=this;this._listener={onDragStart:function(h){f._onDragStart(h)},onDragEnd:function(h){f._onDragEnd(h)},onDragEnter:function(h){f._onDragEnter(h)},onDragOver:function(h){f._onDragOver(h)},onDrop:function(h){f._onDrop(h)},onDestroy:function(h){f._onDestroy(h)}};r.addEventListener("DragStart",this._listener.onDragStart);r.addEventListener("DragEnd", +this._listener.onDragEnd);r.addEventListener("DragEnter",this._listener.onDragEnter);r.addEventListener("DragOver",this._listener.onDragOver);r.addEventListener("Drop",this._listener.onDrop);r.addEventListener("Destroy",this._listener.onDestroy)}s.prototype={destroy:function(){var r=this._view;if(r)r.removeEventListener("DragStart",this._listener.onDragStart),r.removeEventListener("DragEnd",this._listener.onDragEnd),r.removeEventListener("DragEnter",this._listener.onDragEnter),r.removeEventListener("DragOver", +this._listener.onDragOver),r.removeEventListener("Drop",this._listener.onDrop),r.removeEventListener("Destroy",this._listener.onDestroy),this._view=null},_onDestroy:function(){this.destroy()},_onDragStart:function(r){var p=this._view,f=p.getSelection(),p=p.getModel();if(p.getBaseModel)f.start=p.mapOffset(f.start),f.end=p.mapOffset(f.end),p=p.getBaseModel();if(p=p.getText(f.start,f.end))this._dragSelection=f,r.event.dataTransfer.effectAllowed="copyMove",r.event.dataTransfer.setData("Text",p)},_onDragEnd:function(r){var p= +this._view;if(this._dragSelection){this._undoStack&&this._undoStack.startCompoundChange();(r=r.event.dataTransfer.dropEffect==="move")&&p.setText("",this._dragSelection.start,this._dragSelection.end);if(this._dropText){var f=this._dropText,h=this._dropOffset;if(r)if(h>=this._dragSelection.end)h-=this._dragSelection.end-this._dragSelection.start;else if(h>=this._dragSelection.start)h=this._dragSelection.start;p.setText(f,h,h);p.setSelection(h,h+f.length);this._dropText=null;this._dropOffset=-1}this._undoStack&& +this._undoStack.endCompoundChange()}this._dragSelection=null},_onDragEnter:function(r){this._onDragOver(r)},_onDragOver:function(r){var p=r.event.dataTransfer.types;if(p){var f=!this._view.getOptions("readonly");f&&(f=p.contains?p.contains("text/plain"):p.indexOf("text/plain")!==-1);if(!f)r.event.dataTransfer.dropEffect="none"}},_onDrop:function(r){var p=this._view,f=r.event.dataTransfer.getData("Text");if(f)r=p.getOffsetAtLocation(r.x,r.y),this._dragSelection?(this._dropOffset=r,this._dropText=f): +(p.setText(f,r,r),p.setSelection(r,r+f.length))}};return{TextDND:s}}); +define("orion/editor/editor","i18n!orion/editor/nls/messages,orion/editor/keyBinding,orion/editor/eventTarget,orion/editor/tooltip,orion/editor/annotations,orion/editor/util".split(","),function(s,r,p,f,h,l){function k(a){this._textViewFactory=a.textViewFactory;this._undoStackFactory=a.undoStackFactory;this._textDNDFactory=a.textDNDFactory;this._annotationFactory=a.annotationFactory;this._foldingRulerFactory=a.foldingRulerFactory;this._lineNumberRulerFactory=a.lineNumberRulerFactory;this._contentAssistFactory= +a.contentAssistFactory;this._keyBindingFactory=a.keyBindingFactory;this._statusReporter=a.statusReporter;this._domNode=a.domNode;this._foldingRuler=this._overviewRuler=this._lineNumberRuler=this._annotationRuler=this._annotationModel=this._annotationStyler=null;this._dirty=!1;this._title=this._contentAssist=null;this._keyModes=[]}function m(a){var b=this,d=Array.prototype.slice.call(arguments,1);return d.length?function(){return arguments.length?b.apply(a,d.concat(Array.prototype.slice.call(arguments))): +b.apply(a,d)}:function(){return arguments.length?b.apply(a,arguments):b.call(a)}}var e;k.prototype={destroy:function(){this.uninstallTextView();this._textViewFactory=this._undoStackFactory=this._textDNDFactory=this._annotationFactory=this._foldingRulerFactory=this._lineNumberRulerFactory=this._contentAssistFactory=this._keyBindingFactory=this._statusReporter=this._domNode=null},getAnnotationModel:function(){return this._annotationModel},getAnnotationRuler:function(){return this._annotationRuler}, +getAnnotationStyler:function(){return this._annotationStyler},getFoldingRuler:function(){return this._foldingRuler},getLineNumberRuler:function(){return this._lineNumberRuler},getModel:function(){var a=this._textView.getModel();a.getBaseModel&&(a=a.getBaseModel());return a},getOverviewRuler:function(){return this._overviewRuler},getTextView:function(){return this._textView},getTitle:function(){return this._title},getKeyModes:function(){return this._keyModes},isDirty:function(){return this._dirty}, +setAnnotationRulerVisible:function(a){if(this._annotationRulerVisible!==a&&(this._annotationRulerVisible=a,this._annotationRuler)){var b=this._textView;a?b.addRuler(this._annotationRuler,0):b.removeRuler(this._annotationRuler)}},setFoldingRulerVisible:function(a){if(this._foldingRulerVisible!==a&&(this._foldingRulerVisible=a,this._foldingRuler)){var b=this._textView;b.getModel().getBaseModel&&(a?b.addRuler(this._foldingRuler,100):b.removeRuler(this._foldingRuler))}},setDirty:function(a){if(this._dirty!== +a)this._dirty=a,this.onDirtyChanged({type:"DirtyChanged"})},setLineNumberRulerVisible:function(a){if(this._lineNumberRulerVisible!==a&&(this._lineNumberRulerVisible=a,this._lineNumberRuler)){var b=this._textView;a?b.addRuler(this._lineNumberRuler,1):b.removeRuler(this._lineNumberRuler)}},setOverviewRulerVisible:function(a){if(this._overviewRulerVisible!==a&&(this._overviewRulerVisible=a,this._overviewRuler)){var b=this._textView;a?b.addRuler(this._overviewRuler):b.removeRuler(this._overviewRuler)}}, +mapOffset:function(a,b){var d=this._textView.getModel();d.getBaseModel&&(a=d.mapOffset(a,b));return a},getCaretOffset:function(){return this.mapOffset(this._textView.getCaretOffset())},getSelection:function(){var a=this._textView,b=a.getSelection(),a=a.getModel();if(a.getBaseModel)b.start=a.mapOffset(b.start),b.end=a.mapOffset(b.end);return b},getText:function(a,b){var d=this._textView.getModel();d.getBaseModel&&(d=d.getBaseModel());return d.getText(a,b)},_expandOffset:function(a){var b=this._textView.getModel(), +d=this._annotationModel;if(d&&b.getBaseModel)for(a=d.getAnnotations(a,a+1);a.hasNext();)b=a.next(),b.type===h.AnnotationType.ANNOTATION_FOLDING&&b.expand&&(b.expand(),d.modifyAnnotation(b))},setCaretOffset:function(a){var b=this._textView,d=b.getModel();d.getBaseModel&&(this._expandOffset(a),a=d.mapOffset(a,!0));b.setCaretOffset(a)},setText:function(a,b,d){var e=this._textView,f=e.getModel();f.getBaseModel&&(b!==void 0&&(this._expandOffset(b),b=f.mapOffset(b,!0)),d!==void 0&&(this._expandOffset(d), +d=f.mapOffset(d,!0)));e.setText(a,b,d)},setFoldingEnabled:function(a){this.setFoldingRulerVisible(a)},setSelection:function(a,b,d){var e=this._textView,f=e.getModel();f.getBaseModel&&(this._expandOffset(a),this._expandOffset(b),a=f.mapOffset(a,!0),b=f.mapOffset(b,!0));e.setSelection(a,b,d)},moveSelection:function(a,b,d,i){var f=this._textView;this.setSelection(a,b||a,!1);var b=f.getTopPixel(),o=f.getBottomPixel(),a=this.getModel().getLineAtOffset(a),a=f.getLinePixel(a);ao?(o=Math.max(0,a-Math.floor((a< +b?3:1)*(o-b)/4)),(new e({node:f,duration:300,curve:[b,o],onAnimate:function(a){f.setTopPixel(Math.floor(a))},onEnd:function(){f.showSelection();(i===void 0||i)&&f.focus();d&&d()}})).play()):(f.showSelection(),(i===void 0||i)&&f.focus(),d&&d())},checkDirty:function(){this.setDirty(!this._undoStack.isClean())},reportStatus:function(a,b,d){this._statusReporter&&this._statusReporter(a,b,d)},_getTooltipInfo:function(a,b){var d=this._textView,e=this.getAnnotationModel();if(!e)return null;var f=this._annotationStyler; +if(!f)return null;var o=d.getOffsetAtLocation(a,b);if(o===-1)return null;o=this.mapOffset(o);f=f.getAnnotationsByType(e,o,o+1);e=[];for(o=0;o
"}),o.addAnnotationType(h.AnnotationType.ANNOTATION_ERROR), +o.addAnnotationType(h.AnnotationType.ANNOTATION_WARNING),o.addAnnotationType(h.AnnotationType.ANNOTATION_TASK),o.addAnnotationType(h.AnnotationType.ANNOTATION_BOOKMARK);this.setAnnotationRulerVisible(!0);if(o=this._overviewRuler=g.overviewRuler)o.onClick=function(a){a!==void 0&&(a=d.getModel().getLineStart(a),b.moveSelection(b.mapOffset(a)))},o.addAnnotationType(h.AnnotationType.ANNOTATION_CURRENT_SEARCH),o.addAnnotationType(h.AnnotationType.ANNOTATION_MATCHING_SEARCH),o.addAnnotationType(h.AnnotationType.ANNOTATION_ERROR), +o.addAnnotationType(h.AnnotationType.ANNOTATION_WARNING),o.addAnnotationType(h.AnnotationType.ANNOTATION_TASK),o.addAnnotationType(h.AnnotationType.ANNOTATION_BOOKMARK),o.addAnnotationType(h.AnnotationType.ANNOTATION_MATCHING_BRACKET),o.addAnnotationType(h.AnnotationType.ANNOTATION_CURRENT_BRACKET),o.addAnnotationType(h.AnnotationType.ANNOTATION_CURRENT_LINE),o.addAnnotationType(h.AnnotationType.ANNOTATION_READ_OCCURRENCE),o.addAnnotationType(h.AnnotationType.ANNOTATION_WRITE_OCCURRENCE);this.setOverviewRulerVisible(!0)}if(this._lineNumberRulerFactory)this._lineNumberRuler= +this._lineNumberRulerFactory.createLineNumberRuler(this._annotationModel),this._lineNumberRuler.onDblClick=a,this.setLineNumberRulerVisible(!0);if(this._foldingRulerFactory)this._foldingRuler=this._foldingRulerFactory.createFoldingRuler(this._annotationModel),this._foldingRuler.addAnnotationType(h.AnnotationType.ANNOTATION_FOLDING),this.setFoldingRulerVisible(!1);this.dispatchEvent({type:"TextViewInstalled",textView:d})},uninstallTextView:function(){var a=this._textView;if(a)a.destroy(),this._textView= +this._undoStack=this._textDND=this._contentAssist=this._listener=this._annotationModel=this._annotationStyler=this._annotationRuler=this._overviewRuler=this._lineNumberRuler=this._foldingRuler=this._currentLineAnnotation=this._title=null,this._dirty=!1,this._keyModes=[],this.dispatchEvent({type:"TextViewUninstalled",textView:a})},_updateCursorStatus:function(){var a=this.getModel(),b=this.getCaretOffset(),d=a.getLineAtOffset(b),a=a.getLineStart(d);b-=a;for(a=0;a=e.offset&&a.end<=e.offset+e.length)b=e.length,e.length=a.start-e.offset+a.text.length+(e.offset+e.length-a.end),c=e.length-b,b=!0}b?this.linkedModeEscapePosition+=c:this.cancel()}.bind(this)}}a.prototype={createUndoStack:function(a){var a=a.getTextView(),b=new r.UndoStack(a,200);a.setAction("undo",function(){b.undo();return!0}, +{name:s.undo});a.setAction("redo",function(){b.redo();return!0},{name:s.redo});return b}};b.prototype={createLineNumberRuler:function(a){return new f.LineNumberRuler(a,"left",{styleClass:"ruler lines"},{styleClass:"rulerLines odd"},{styleClass:"rulerLines even"})}};d.prototype={createFoldingRuler:function(a){return new f.FoldingRuler(a,"left",{styleClass:"ruler folding"})}};i.prototype={createAnnotationModel:function(a){return new h.AnnotationModel(a)},createAnnotationStyler:function(a,b){return new h.AnnotationStyler(a, +b)},createAnnotationRulers:function(a){var b=new f.AnnotationRuler(a,"left",{styleClass:"ruler annotations"}),a=new f.OverviewRuler(a,"right",{styleClass:"ruler overview"});return{annotationRuler:b,overviewRuler:a}}};g.prototype={createTextDND:function(a,b){return new k.TextDND(a.getTextView(),b)}};o.prototype={init:function(){var a=this;this._incrementalFindListener={onVerify:function(b){var c=a.editor,d=c.getModel(),f=c.mapOffset(b.start),i=c.mapOffset(b.end),f=d.getText(f,i),d=a._incrementalFindPrefix; +if((d=d.match(RegExp("^"+m.escape(f),"i")))&&d.length>0)d=a._incrementalFindPrefix+=b.text,a.editor.reportStatus(e.formatMessage(s.incrementalFind,d)),f=c.getSelection().start,(f=c.getModel().find({string:d,start:f,caseInsensitive:d.toLowerCase()===d}).next())?(a._incrementalFindSuccess=!0,a._incrementalFindIgnoreSelection=!0,c.moveSelection(f.start,f.end),a._incrementalFindIgnoreSelection=!1):(c.reportStatus(e.formatMessage(s.incrementalFindNotFound,d),"error"),a._incrementalFindSuccess=!1),b.text= +null},onSelection:function(){a._incrementalFindIgnoreSelection||a.toggleIncrementalFind()}};this._lastEditListener={onModelChanged:function(b){if(a.editor.isDirty())a._lastEditLocation=b.start+b.addedCharCount}};this.textView.addEventListener("ModelChanged",this._lastEditListener.onModelChanged);this.textView.setKeyBinding(new p.KeyBinding("k",!0),"findNext");this.textView.setAction("findNext",function(){if(this._searcher){var a=this.textView.getSelection();a.startc.start?c.end-1:c.end);if(d!==e){var f=[];f.push("");for(var i=d;i<=e;i++)f.push(b.getLine(i,!0));var i=b.getLineStart(d),b=b.getLineEnd(e,!0),g=this.textView.getOptions("tabSize","expandTab"),g=g.expandTab?Array(g.tabSize+ +1).join(" "):"\t";a.setText(f.join(g),i,b);a.setSelection(i===c.start?c.start:c.start+g.length,c.end+(e-d+1)*g.length);return!0}a=a.getKeyModes();for(c=0;cc.start?c.end-1:c.end),f=this.textView.getOptions("tabSize"), +i=Array(f+1).join(" "),g=[],j=0,o=0,k=d;k<=e;k++){var h=b.getLine(k,!0);if(b.getLineStart(k)!==b.getLineEnd(k))if(h.indexOf("\t")===0)h=h.substring(1),j++;else if(h.indexOf(i)===0)h=h.substring(f),j+=f;else return!0;k===d&&(o=j);g.push(h)}d=b.getLineStart(d);f=b.getLineEnd(e,!0);b=b.getLineStart(e);a.setText(g.join(""),d,f);g=d===c.start?c.start:c.start-o;c=Math.max(g,c.end-j+(c.end===b+1&&c.start!==c.end?1:0));a.setSelection(g,c);return!0}}.bind(this),{name:s.unindentLines});this.textView.setKeyBinding(new p.KeyBinding(38, +!1,!1,!0),"moveLinesUp");this.textView.setAction("moveLinesUp",function(){if(this.textView.getOptions("readonly"))return!1;var a=this.editor,b=a.getModel(),c=a.getSelection(),d=b.getLineAtOffset(c.start);if(d===0)return!0;var e=b.getLineAtOffset(c.end>c.start?c.end-1:c.end),f=b.getLineCount(),c=b.getLineStart(d-1),i=b.getLineStart(d),g=b.getLineEnd(e,!0),j=b.getText(i,g),k=0;e===f-1&&(e=b.getLineEnd(d-1),d=b.getLineEnd(d-1,!0),j+=b.getText(e,d),i=e,k=d-e);this.startUndo();a.setText("",i,g);a.setText(j, +c,c);a.setSelection(c,c+j.length-k);this.endUndo();return!0}.bind(this),{name:s.moveLinesUp});this.textView.setKeyBinding(new p.KeyBinding(40,!1,!1,!0),"moveLinesDown");this.textView.setAction("moveLinesDown",function(){if(this.textView.getOptions("readonly"))return!1;var a=this.editor,b=a.getModel(),c=a.getSelection(),d=b.getLineAtOffset(c.start),e=b.getLineAtOffset(c.end>c.start?c.end-1:c.end),f=b.getLineCount();if(e===f-1)return!0;var d=b.getLineStart(d),c=b.getLineEnd(e,!0),i=b.getLineEnd(e+1, +!0)-(c-d),g=0;e!==f-2?b=b.getText(d,c):(e=b.getLineEnd(e),b=b.getText(e,c)+b.getText(d,e),g+=c-e);this.startUndo();a.setText("",d,c);a.setText(b,i,i);a.setSelection(i+g,i+g+b.length);this.endUndo();return!0}.bind(this),{name:s.moveLinesDown});this.textView.setKeyBinding(new p.KeyBinding(38,!0,!1,!0),"copyLinesUp");this.textView.setAction("copyLinesUp",function(){if(this.textView.getOptions("readonly"))return!1;var a=this.editor,b=a.getModel(),c=a.getSelection(),d=b.getLineAtOffset(c.start),c=b.getLineAtOffset(c.end> +c.start?c.end-1:c.end),d=b.getLineStart(d),e=b.getLineEnd(c,!0),f=b.getLineCount(),i="",e=b.getText(d,e);c===f-1&&(e+=i=b.getLineDelimiter());a.setText(e,d,d);a.setSelection(d,d+e.length-i.length);return!0}.bind(this),{name:s.copyLinesUp});this.textView.setKeyBinding(new p.KeyBinding(40,!0,!1,!0),"copyLinesDown");this.textView.setAction("copyLinesDown",function(){if(this.textView.getOptions("readonly"))return!1;var a=this.editor,b=a.getModel(),c=a.getSelection(),d=b.getLineAtOffset(c.start),c=b.getLineAtOffset(c.end> +c.start?c.end-1:c.end),e=b.getLineStart(d),d=b.getLineEnd(c,!0),f=b.getLineCount(),i="",e=b.getText(e,d);c===f-1&&(e=(i=b.getLineDelimiter())+e);a.setText(e,d,d);a.setSelection(d+i.length,d+e.length);return!0}.bind(this),{name:s.copyLinesDown});this.textView.setKeyBinding(new p.KeyBinding("d",!0,!1,!1),"deleteLines");this.textView.setAction("deleteLines",function(){if(this.textView.getOptions("readonly"))return!1;var a=this.editor,b=a.getSelection(),c=a.getModel(),d=c.getLineAtOffset(b.start),b=c.getLineAtOffset(b.end> +b.start?b.end-1:b.end),d=c.getLineStart(d),c=c.getLineEnd(b,!0);a.setText("",d,c);return!0}.bind(this),{name:s.deleteLines});this.textView.setKeyBinding(new p.KeyBinding("l",!0),"gotoLine");this.textView.setAction("gotoLine",function(){var a=this.editor,b=a.getModel().getLineAtOffset(a.getCaretOffset());if(b=prompt(s.gotoLinePrompty,b+1))b=parseInt(b,10),a.onGotoLine(b-1,0);return!0}.bind(this),{name:s.gotoLine});this.textView.setKeyBinding(new p.KeyBinding(190,!0),"nextAnnotation");this.textView.setAction("nextAnnotation", +function(){var a=this.editor,b=a.getAnnotationModel();if(!b)return!0;for(var c=a.getModel(),d=a.getCaretOffset(),b=b.getAnnotations(d,c.getCharCount());b.hasNext();){var e=b.next();if(!(e.start<=d)&&!(e.type!==h.AnnotationType.ANNOTATION_ERROR&&e.type!==h.AnnotationType.ANNOTATION_WARNING&&e.type!==h.AnnotationType.ANNOTATION_TASK&&e.type!==h.AnnotationType.ANNOTATION_BOOKMARK)){var f=l.Tooltip.getTooltip(this.textView);if(!f){a.moveSelection(e.start);break}var i=c.getLineAtOffset(e.start),g=this.textView; +a.moveSelection(e.start,e.start,function(){setTimeout(function(){f.setTarget({getTooltipInfo:function(){var a=g.convert({x:g.getLocationAtOffset(e.start).x,y:g.getLocationAtOffset(c.getLineStart(i)).y},"document","page");return{contents:[e],x:a.x,y:a.y+Math.floor(g.getLineHeight(i)*1.33)}}},0)},0)});break}}return!0}.bind(this),{name:s.nextAnnotation});this.textView.setKeyBinding(new p.KeyBinding(188,!0),"previousAnnotation");this.textView.setAction("previousAnnotation",function(){var a=this.editor, +b=a.getAnnotationModel();if(!b)return!0;for(var c=a.getModel(),d=a.getCaretOffset(),b=b.getAnnotations(0,d),e=null;b.hasNext();){var f=b.next();f.start>=d||f.type!==h.AnnotationType.ANNOTATION_ERROR&&f.type!==h.AnnotationType.ANNOTATION_WARNING&&f.type!==h.AnnotationType.ANNOTATION_TASK&&f.type!==h.AnnotationType.ANNOTATION_BOOKMARK||(e=f)}if(e){var i=c.getLineAtOffset(e.start),g=l.Tooltip.getTooltip(this.textView);if(!g)return a.moveSelection(e.start),!0;var j=this.textView;a.moveSelection(e.start, +e.start,function(){setTimeout(function(){g.setTarget({getTooltipInfo:function(){var a=j.convert({x:j.getLocationAtOffset(e.start).x,y:j.getLocationAtOffset(c.getLineStart(i)).y},"document","page");return{contents:[e],x:a.x,y:a.y+Math.floor(j.getLineHeight(i)*1.33)}}},0)},0)})}return!0}.bind(this),{name:s.prevAnnotation});this.textView.setKeyBinding(new p.KeyBinding("e",!0,!1,!0,!1),"expand");this.textView.setAction("expand",function(){var a=this.editor,b=a.getAnnotationModel();if(!b)return!0;var c= +a.getModel(),a=a.getCaretOffset(),d=c.getLineAtOffset(a),a=c.getLineStart(d),d=c.getLineEnd(d,!0);c.getBaseModel&&(a=c.mapOffset(a),d=c.mapOffset(d),c.getBaseModel());for(var e,c=b.getAnnotations(a,d);!e&&c.hasNext();)a=c.next(),a.type===h.AnnotationType.ANNOTATION_FOLDING&&(a.expanded||(e=a));e&&!e.expanded&&(e.expand(),b.modifyAnnotation(e));return!0}.bind(this),{name:s.expand});this.textView.setKeyBinding(new p.KeyBinding("c",!0,!1,!0,!1),"collapse");this.textView.setAction("collapse",function(){var a= +this.editor,b=a.getAnnotationModel();if(!b)return!0;var c=a.getModel(),d=a.getCaretOffset(),e=c.getLineAtOffset(d),d=c.getLineStart(e),e=c.getLineEnd(e,!0);c.getBaseModel&&(d=c.mapOffset(d),e=c.mapOffset(e),c.getBaseModel());for(var f,c=b.getAnnotations(d,e);!f&&c.hasNext();)d=c.next(),d.type===h.AnnotationType.ANNOTATION_FOLDING&&(f=d);f&&f.expanded&&(a.setCaretOffset(f.start),f.collapse(),b.modifyAnnotation(f));return!0}.bind(this),{name:s.collapse});this.textView.setKeyBinding(new p.KeyBinding("e", +!0,!0,!0,!1),"expandAll");this.textView.setAction("expandAll",function(){var a=this.editor,b=a.getAnnotationModel();if(!b)return!0;var a=a.getModel(),c=b.getAnnotations(0,a.getCharCount());for(this.textView.setRedraw(!1);c.hasNext();)a=c.next(),a.type===h.AnnotationType.ANNOTATION_FOLDING&&!a.expanded&&(a.expand(),b.modifyAnnotation(a));this.textView.setRedraw(!0);return!0}.bind(this),{name:s.expandAll});this.textView.setKeyBinding(new p.KeyBinding("c",!0,!0,!0,!1),"collapseAll");this.textView.setAction("collapseAll", +function(){var a=this.editor,b=a.getAnnotationModel();if(!b)return!0;var a=a.getModel(),c=b.getAnnotations(0,a.getCharCount());for(this.textView.setRedraw(!1);c.hasNext();)a=c.next(),a.type===h.AnnotationType.ANNOTATION_FOLDING&&a.expanded&&(a.collapse(),b.modifyAnnotation(a));this.textView.setRedraw(!0);return!0}.bind(this),{name:s.collapseAll});this.textView.setKeyBinding(new p.KeyBinding("q",!e.isMac,!1,!1,e.isMac),"lastEdit");this.textView.setAction("lastEdit",function(){typeof this._lastEditLocation=== +"number"&&this.editor.showSelection(this._lastEditLocation);return!0}.bind(this),{name:s.lastEdit})},toggleIncrementalFind:function(){(this._incrementalFindActive=!this._incrementalFindActive)?(this.editor.reportStatus(e.formatMessage(s.incrementalFind,this._incrementalFindPrefix)),this.textView.addEventListener("Verify",this._incrementalFindListener.onVerify),this.textView.addEventListener("Selection",this._incrementalFindListener.onSelection)):(this._incrementalFindPrefix="",this.editor.reportStatus(""), +this.textView.removeEventListener("Verify",this._incrementalFindListener.onVerify),this.textView.removeEventListener("Selection",this._incrementalFindListener.onSelection),this.textView.setCaretOffset(this.textView.getCaretOffset()))},startUndo:function(){this.undoStack&&this.undoStack.startCompoundChange()},endUndo:function(){this.undoStack&&this.undoStack.endCompoundChange()},cancel:function(){this.toggleIncrementalFind()},isActive:function(){return this._incrementalFindActive},isStatusActive:function(){return this._incrementalFindActive}, +lineUp:function(){if(this._incrementalFindActive){var a=this._incrementalFindPrefix;if(a.length===0)return!1;var b=this.editor,c=b.getModel(),c=this._incrementalFindSuccess?b.getCaretOffset()-a.length-1:c.getCharCount()-1;(c=b.getModel().find({string:a,start:c,reverse:!0,caseInsensitive:a.toLowerCase()===a}).next())?(this._incrementalFindIgnoreSelection=this._incrementalFindSuccess=!0,b.moveSelection(c.start,c.end),this._incrementalFindIgnoreSelection=!1,b.reportStatus(e.formatMessage(s.incrementalFind, +a))):(b.reportStatus(e.formatMessage(s.incrementalFindNotFound,a),"error"),this._incrementalFindSuccess=!1);return!0}return!1},lineDown:function(){if(this._incrementalFindActive){var a=this._incrementalFindPrefix;if(a.length===0)return!1;var b=this.editor,c=0;this._incrementalFindSuccess&&(c=b.getSelection().start+1);(c=b.getModel().find({string:a,start:c,caseInsensitive:a.toLowerCase()===a}).next())?(this._incrementalFindIgnoreSelection=this._incrementalFindSuccess=!0,b.moveSelection(c.start,c.end), +this._incrementalFindIgnoreSelection=!1,b.reportStatus(e.formatMessage(s.incrementalFind,a))):(b.reportStatus(e.formatMessage(s.incrementalFindNotFound,a),"error"),this._incrementalFindSuccess=!1);return!0}return!1},enter:function(){return!1}};c.prototype={startUndo:function(){this.undoStack&&this.undoStack.startCompoundChange()},endUndo:function(){this.undoStack&&this.undoStack.endCompoundChange()},init:function(){function a(b,c,d){var e=b.getLineAtOffset(c),f=b.getLineAtOffset(d),i,g,j,k,o,h;for(i= +e;i>=0;i--)if(g=b.getLine(i),j=i===e?c-b.getLineStart(e):g.length,k=g.lastIndexOf("/*",j),g=g.lastIndexOf("*/",j),g>k)break;else if(k!==-1){o=b.getLineStart(i)+k;break}for(i=f;ic.start?c.end-1:c.end),f=!0,i=[],g,j,k=d;k<=e;k++)if(g= +b.getLine(k,!0),i.push(g),!f||(j=g.indexOf("//"))===-1)f=!1;else if(j!==0){var o;for(o=0;o0){for(var g=e.substring(0,d),d=f;d0?this.linkedModeCurrentPositionIndex-1:this.linkedModePositions.length-1;this.selectTextForLinkedModePosition(this.linkedModePositions[this.linkedModeCurrentPositionIndex]); +return!0}.bind(this));this.editor.reportStatus(s.linkedModeEntered,null,!0)}},isActive:function(){return this.linkedModeActive},isStatusActive:function(){return this.linkedModeActive},enter:function(){this.cancel();return!0},cancel:function(a){if(this.linkedModeActive)this.linkedModeActive=!1,this.textView.removeEventListener("Verify",this.linkedModeListener.onVerify),this.textView.setKeyBinding(new p.KeyBinding(9),"tab"),this.textView.setKeyBinding(new p.KeyBinding(9,!1,!0),"shiftTab"),a||this.textView.setCaretOffset(this.linkedModeEscapePosition, +!1),this.editor.reportStatus(s.linkedModeExited,null,!0)},lineUp:function(){this.cancel(!0);return!1},lineDown:function(){this.cancel(!0);return!1},selectTextForLinkedModePosition:function(a){this.textView.setSelection(a.offset,a.offset+a.length)}};return{UndoFactory:a,LineNumberRulerFactory:b,FoldingRulerFactory:d,AnnotationFactory:i,TextDNDFactory:g,TextActions:o,SourceCodeActions:c,LinkedMode:j}}); +(function(s,r){typeof define==="function"&&define.amd?define("orion/Deferred",r):typeof exports==="object"?module.exports=r():(s.orion=s.orion||{},s.orion.Deferred=r())})(this,function(){function s(){for(var a;a=k.shift()||m.shift();)a();e=!1}function r(a,b){(b?m:k).push(a);e||(e=!0,b?setTimeout(s,0):s())}function p(a){return function(){a.apply(null,arguments)}}function f(){}function h(){var a=Error("Cancel");a.name="Cancel";return a}function l(){function a(){for(var a;a=e.shift();){var c=a.deferred, +g=d==="resolved"?"resolve":"reject";if(typeof a[g]==="function")try{var k=a[g](b);k&&typeof k.then==="function"?(c.cancel=k.cancel||f,k.then(p(c.resolve),p(c.reject),c.progress)):c.resolve(k)}catch(h){c.reject(h)}else c[g](b)}}var b,d,e=[],g=this;this.reject=function(f){d||(d="rejected",b=f,e.length&&r(a));return g.promise};this.resolve=function(f){d||(d="resolved",b=f,e.length&&r(a));return g.promise};this.progress=function(a){d||e.forEach(function(b){b.progress&&b.progress(a)});return g.promise}; +this.cancel=function(){d||g.reject(h())};this.then=function(b,c,f){var b={resolve:b,reject:c,progress:f,deferred:new l},g=b.deferred,k=this.cancel.bind(this),h=function(){r(function(){(g.cancel===h?k:g.cancel)()},!0)};g.cancel=h;c=g.promise;c.cancel=function(){g.cancel()};e.push(b);d&&r(a,!0);return c};this.promise={then:this.then,cancel:this.cancel}}var k=[],m=[],e=!1;l.all=function(a,b){function d(a,b){c||(k[a]=b,--f===0&&j.resolve(k))}function e(a,f){if(!c){if(b)try{d(a,b(f));return}catch(i){f= +i}j.reject(f)}}var f=a.length,k=[],c=!1,j=new l;j.then(null,function(){c=!0;a.forEach(function(a){a.cancel&&a.cancel()})});f===0?j.resolve(k):a.forEach(function(a,b){a.then(d.bind(null,b),e.bind(null,b))});return j.promise};l.when=function(a,b,d,e){var f;if(!(a&&typeof a.then==="function"))f=new l,f.resolve(a),a=f.promise;return a.then(b,d,e)};return l}); +define("orion/editor/contentAssist",["i18n!orion/editor/nls/messages","orion/editor/keyBinding","orion/editor/eventTarget","orion/Deferred","orion/editor/util"],function(s,r,p,f,h){var l,k,m;function e(a){this.textView=a;this.state=l;this.providers=[];var b=this;this.contentAssistListener={onModelChanging:function(a){b.isDeactivatingChange(a)?b.setState(l):b.state===k&&b.setState(m)},onScroll:function(){b.setState(l)},onSelection:function(){var a=b.state;if(a===k||a===m)b.computeProposals(),b.setState(m)}}; +a.setKeyBinding(h.isMac?new r.KeyBinding(" ",!1,!1,!1,!0):new r.KeyBinding(" ",!0),"contentAssist");a.setAction("contentAssist",function(){b.activate();return!0},{name:s.contentAssist})}function a(a,b){this.contentAssist=a;this.widget=b;this.proposals=[];var d=this;this.contentAssist.addEventListener("ProposalsComputed",function(a){d.proposals=a.data.proposals;d.selectedIndex=d.proposals.length?0:-1})}function b(a,b){this.contentAssist=a;this.textView=this.contentAssist.getTextView();this.isShowing= +this.textViewListenerAdded=!1;var d=this.textView.getOptions("parent").ownerDocument;this.parentNode=typeof b==="string"?d.getElementById(b):b;if(!this.parentNode){this.parentNode=h.createElement(d,"div");this.parentNode.className="contentassist";var c=d.getElementsByTagName("body")[0];if(c)c.appendChild(this.parentNode);else throw Error("parentNode is required");}var e=this;this.textViewListener={onMouseDown:function(a){a.event.target.parentElement!==e.parentNode&&e.contentAssist.deactivate()}}; +this.contentAssist.addEventListener("ProposalsComputed",function(a){e.setProposals(a.data.proposals);e.show();if(!e.textViewListenerAdded)e.textView.addEventListener("MouseDown",e.textViewListener.onMouseDown),e.textViewListenerAdded=!0});this.contentAssist.addEventListener("Deactivating",function(){e.setProposals([]);e.hide();if(e.textViewListenerAdded)e.textView.removeEventListener("MouseDown",e.textViewListener.onMouseDown),e.textViewListenerAdded=!1;e.textViewListenerAdded=!1});this.scrollListener= +function(){e.isShowing&&e.position()};d.addEventListener("scroll",this.scrollListener)}l=1;k=2;m=3;var d={selected:" selected",hr:"proposal-hr",emphasis:"proposal-emphasis",noemphasis:"proposal-noemphasis",dfault:"proposal-default"};e.prototype={apply:function(a){if(!a)return!1;var b=this.textView.getCaretOffset(),d={proposal:a,start:b,end:b};this.setState(l);this.textView.setText(a.proposal||a,b,b);this.dispatchEvent({type:"ProposalApplied",data:d});return!0},activate:function(){this.state===l&& +this.setState(k)},deactivate:function(){this.setState(l)},getTextView:function(){return this.textView},isActive:function(){return this.state===k||this.state===m},isDeactivatingChange:function(a){var b=a.removedCharCount>0&&a.addedCharCount===0,d=this.textView,d=a.start+1<=d.getModel().getCharCount()&&/^\s*$/.test(d.getText(a.start,a.start+1));return a.removedLineCount>0||a.addedLineCount>0||b&&d},setState:function(a){var b;a===k?b="Activating":a===l&&(b="Deactivating");b&&this.dispatchEvent({type:b}); +this.state=a;this.onStateChange(a)},onStateChange:function(a){if(a===l){if(this.listenerAdded)this.textView.removeEventListener("ModelChanging",this.contentAssistListener.onModelChanging),this.textView.removeEventListener("Scroll",this.contentAssistListener.onScroll),this.textView.removeEventListener("Selection",this.contentAssistListener.onSelection),this.listenerAdded=!1}else if(a===k){if(!this.listenerAdded)this.textView.addEventListener("ModelChanging",this.contentAssistListener.onModelChanging), +this.textView.addEventListener("Scroll",this.contentAssistListener.onScroll),this.textView.addEventListener("Selection",this.contentAssistListener.onSelection),this.listenerAdded=!0;this.computeProposals()}},computeProposals:function(){var a=this;this._computeProposals(this.textView.getCaretOffset()).then(function(b){a.dispatchEvent({type:"ProposalsComputed",data:{proposals:b}})})},getPrefixStart:function(a){for(;a>0&&/[A-Za-z0-9_]/.test(this.textView.getText(a-1,a));)a--;return a},handleError:function(a){typeof console!== +"undefined"&&(console.log("Error retrieving content assist proposals"),console.log(a))},_computeProposals:function(a){var b=this.providers,d=this.textView,c=d.getModel(),e=d.getText(),k={line:c.getLine(c.getLineAtOffset(a)),prefix:d.getText(this.getPrefixStart(a),a),selection:d.getSelection()},h=this,b=b.map(function(b){var c=b.computeProposals||b.getProposals,d;try{typeof c==="function"&&(d=h.progress?h.progress.progress(c.apply(b,[e,a,k]),"Generating content assist proposal"):c.apply(b,[e,a,k]))}catch(g){h.handleError(g)}return f.when(d)}); +return f.all(b,this.handleError).then(function(a){return a.reduce(function(a,b){return b instanceof Array?a.concat(b):a},[])})},setProviders:function(a){this.providers=a.slice(0)},setProgress:function(a){this.progress=a}};p.EventTarget.addMixin(e.prototype);a.prototype={cancel:function(){this.getContentAssist().deactivate()},getContentAssist:function(){return this.contentAssist},isActive:function(){return this.getContentAssist().isActive()},lineUp:function(){for(var a=this.selectedIndex===0?this.proposals.length- +1:this.selectedIndex-1;this.proposals[a].unselectable&&a>0;)a--;this.selectedIndex=a;this.widget&&this.widget.setSelectedIndex(this.selectedIndex);return!0},lineDown:function(){for(var a=this.selectedIndex===this.proposals.length-1?0:this.selectedIndex+1;this.proposals[a].unselectable&&a=0)c.className=c.className.substring(0, +f)+c.className.substring(f+d.selected.length);c===a&&(c.className+=d.selected,this.parentNode.setAttribute("aria-activedescendant",c.id),c.focus(),c.offsetTopthis.parentNode.scrollTop+this.parentNode.clientHeight&&c.scrollIntoView(!1))}},setProposals:function(a){this.proposals=a},show:function(){if(this.proposals.length===0)this.hide();else{this.parentNode.innerHTML="";for(var a=0;ab.documentElement.clientHeight)this.parentNode.style.top=a.y-this.parentNode.offsetHeight-this.textView.getLineHeight()+"px";if(a.x+this.parentNode.offsetWidth>d)this.parentNode.style.left=d-this.parentNode.offsetWidth+"px"}};return{ContentAssist:e,ContentAssistMode:a, +ContentAssistWidget:b}}); +define("orion/editor/cssContentAssist",[],function(){function s(){}var r="alignment-adjust,alignment-baseline,animation,animation-delay,animation-direction,animation-duration,animation-iteration-count,animation-name,animation-play-state,animation-timing-function,appearance,azimuth,backface-visibility,background,background-attachment,background-clip,background-color,background-image,background-origin,background-position,background-repeat,background-size,baseline-shift,binding,bleed,bookmark-label,bookmark-level,bookmark-state,bookmark-target,border,border-bottom,border-bottom-color,border-bottom-left-radius,border-bottom-right-radius,border-bottom-style,border-bottom-width,border-collapse,border-color,border-image,border-image-outset,border-image-repeat,border-image-slice,border-image-source,border-image-width,border-left,border-left-color,border-left-style,border-left-width,border-radius,border-right,border-right-color,border-right-style,border-right-width,border-spacing,border-style,border-top,border-top-color,border-top-left-radius,border-top-right-radius,border-top-style,border-top-width,border-width,bottom,box-align,box-decoration-break,box-direction,box-flex,box-flex-group,box-lines,box-ordinal-group,box-orient,box-pack,box-shadow,box-sizing,break-after,break-before,break-inside,caption-side,clear,clip,color,color-profile,column-count,column-fill,column-gap,column-rule,column-rule-color,column-rule-style,column-rule-width,column-span,column-width,columns,content,counter-increment,counter-reset,crop,cue,cue-after,cue-before,cursor,direction,display,dominant-baseline,drop-initial-after-adjust,drop-initial-after-align,drop-initial-before-adjust,drop-initial-before-align,drop-initial-size,drop-initial-value,elevation,empty-cells,fit,fit-position,flex-align,flex-flow,flex-inline-pack,flex-order,flex-pack,float,float-offset,font,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,grid-columns,grid-rows,hanging-punctuation,height,hyphenate-after,hyphenate-before,hyphenate-character,hyphenate-lines,hyphenate-resource,hyphens,icon,image-orientation,image-rendering,image-resolution,inline-box-align,left,letter-spacing,line-height,line-stacking,line-stacking-ruby,line-stacking-shift,line-stacking-strategy,list-style,list-style-image,list-style-position,list-style-type,margin,margin-bottom,margin-left,margin-right,margin-top,mark,mark-after,mark-before,marker-offset,marks,marquee-direction,marquee-loop,marquee-play-count,marquee-speed,marquee-style,max-height,max-width,min-height,min-width,move-to,nav-down,nav-index,nav-left,nav-right,nav-up,opacity,orphans,outline,outline-color,outline-offset,outline-style,outline-width,overflow,overflow-style,overflow-x,overflow-y,padding,padding-bottom,padding-left,padding-right,padding-top,page,page-break-after,page-break-before,page-break-inside,page-policy,pause,pause-after,pause-before,perspective,perspective-origin,phonemes,pitch,pitch-range,play-during,position,presentation-level,punctuation-trim,quotes,rendering-intent,resize,rest,rest-after,rest-before,richness,right,rotation,rotation-point,ruby-align,ruby-overhang,ruby-position,ruby-span,size,speak,speak-header,speak-numeral,speak-punctuation,speech-rate,stress,string-set,table-layout,target,target-name,target-new,target-position,text-align,text-align-last,text-decoration,text-emphasis,text-height,text-indent,text-justify,text-outline,text-shadow,text-transform,text-wrap,top,transform,transform-origin,transform-style,transition,transition-delay,transition-duration,transition-property,transition-timing-function,unicode-bidi,vertical-align,visibility,voice-balance,voice-duration,voice-family,voice-pitch,voice-pitch-range,voice-rate,voice-stress,voice-volume,volume,white-space,white-space-collapse,widows,width,word-break,word-spacing,word-wrap,z-index".split(",");s.prototype= +{computeProposals:function(p,f){var h;for(h=f;h&&/[A-Za-z\-]/.test(p.charAt(h-1));)h--;h=h?p.substring(h,f):"";for(var l=[],k=0;k0;){var h=r.charAt(p--);if(h==="\n"||h==="\r")break;f=/\s/.test(h)?h.concat(f):""}return f},computeProposals:function(r,p,f){function h(a){return a.substring(f.prefix.length)}var l=[];if(r.length===0)return l.push({proposal:'\n\n\t\n\t\t\n\t\tMy Document\n\t\n\t\n\t\t

A basic HTML document

\n\t\t

\n\t\t\t\n\t\t

\n\t\n', +description:"Simple HTML document",escapePosition:p+152}),l;var k=f.prefix;if(r.charAt(p-k.length-1)!=="<")return l;for(var m,e,a="abbr,b,button,canvas,cite,command,dd,del,dfn,dt,em,embed,font,h1,h2,h3,h4,h5,h6,i,ins,kbd,label,li,mark,meter,object,option,output,progress,q,rp,rt,samp,small,strong,sub,sup,td,time,title,tt,u,var".split(","),b=0;b",m=p+m.length-k.length+1,l.push({proposal:h(e),description:"<"+e,escapePosition:m}));a="address,article,aside,audio,bdo,blockquote,body,caption,code,colgroup,datalist,details,div,fieldset,figure,footer,form,head,header,hgroup,iframe,legend,map,menu,nav,noframes,noscript,optgroup,p,pre,ruby,script,section,select,span,style,tbody,textarea,tfoot,th,thead,tr,video".split(","); +r=this.leadingWhitespace(r,p);for(b=0;b\n"+r+"\t\n"+r+"",m=p+m.length-k.length+r.length+3,l.push({proposal:h(e),description:"<"+e,escapePosition:m}));a="area,base,br,col,hr,input,link,meta,param,keygen,source".split(",");for(b=0;b",m=p+m.length-k.length+2,l.push({proposal:h(e),description:"<"+e,escapePosition:m}));"img".indexOf(k)===0&&(e='img src="" alt="Image"/>',l.push({proposal:h(e),description:"<"+ +e,escapePosition:p+9-k.length}));k==="a"&&l.push({proposal:h('a href="">'),description:" - HTML anchor element",escapePosition:p+7});"ul".indexOf(k)===0&&(e="
    - unordered list",m=p-k.length+r.length+9,l.push({proposal:h("ul>\n"+r+"\t
  • \n"+r+"
"),description:e,escapePosition:m}));"ol".indexOf(k)===0&&(e="
    - ordered list",m=p-k.length+r.length+9,l.push({proposal:h("ol>\n"+r+"\t
  1. \n"+r+"
"),description:e,escapePosition:m}));"dl".indexOf(k)===0&&(e="
- definition list", +m=p-k.length+r.length+9,l.push({proposal:h("dl>\n"+r+"\t
\n"+r+"\t
\n"+r+"
"),description:e,escapePosition:m}));"table".indexOf(k)===0&&(e=" - basic HTML table",m=p-k.length+r.length*2+19,l.push({proposal:h("table>\n"+r+"\t\n"+r+"\t\t\n"+r+"\t\n"+r+"
"),description:e,escapePosition:m}));return l}};return{HTMLContentAssistProvider:s}}); +define("orion/editor/jsTemplateContentAssist",[],function(){function s(f,l,k){var m=k-f.length,e=[],a="";for(k-=1;k>0;){var b=l.charAt(k--);if(b==="\n"||b==="\r")break;a=/\s/.test(b)?b.concat(a):""}l=a;"if".indexOf(f)===0&&(k="if - if statement",a=[{offset:m+4,length:9}],b=m+l.length+18,e.push({proposal:("if (condition) {\n"+l+"\t\n"+l+"}").substring(f.length),description:k,positions:a,escapePosition:b}),k="if - if else statement",a=[{offset:m+4,length:9}],b=m+l.length+18,e.push({proposal:("if (condition) {\n"+ +l+"\t\n"+l+"} else {\n"+l+"\t\n"+l+"}").substring(f.length),description:k,positions:a,escapePosition:b}));"for".indexOf(f)===0&&(k="for - iterate over array",a=[{offset:m+9,length:1},{offset:m+20,length:5}],b=m+l.length+42,e.push({proposal:("for (var i = 0; i < array.length; i++) {\n"+l+"\t\n"+l+"}").substring(f.length),description:k,positions:a,escapePosition:b}),k="for..in - iterate over properties of an object",a=[{offset:m+9,length:8},{offset:m+21,length:6}],b=m+2*l.length+73,e.push({proposal:("for (var property in object) {\n"+ +l+"\tif (object.hasOwnProperty(property)) {\n"+l+"\t\t\n"+l+"\t}\n"+l+"}").substring(f.length),description:k,positions:a,escapePosition:b}));"while".indexOf(f)===0&&(k="while - while loop with condition",a=[{offset:m+7,length:9}],b=m+l.length+21,e.push({proposal:("while (condition) {\n"+l+"\t\n"+l+"}").substring(f.length),description:k,positions:a,escapePosition:b}));"do".indexOf(f)===0&&(k="do - do while loop with condition",a=[{offset:m+16,length:9}],b=m+l.length+6,e.push({proposal:("do {\n"+l+ +"\t\n"+l+"} while (condition);").substring(f.length),description:k,positions:a,escapePosition:b}));"switch".indexOf(f)===0&&(k="switch - switch case statement",a=[{offset:m+8,length:10},{offset:m+28,length:6}],b=m+2*l.length+38,e.push({proposal:("switch (expression) {\n"+l+"\tcase value1:\n"+l+"\t\t\n"+l+"\t\tbreak;\n"+l+"\tdefault:\n"+l+"}").substring(f.length),description:k,positions:a,escapePosition:b}));"try".indexOf(f)===0&&(k="try - try..catch statement",b=m+l.length+7,e.push({proposal:("try {\n"+ +l+"\t\n"+l+"} catch (err) {\n"+l+"}").substring(f.length),description:k,escapePosition:b}),k="try - try..catch statement with finally block",b=m+l.length+7,e.push({proposal:("try {\n"+l+"\t\n"+l+"} catch (err) {\n"+l+"} finally {\n"+l+"}").substring(f.length),description:k,escapePosition:b}));return e}function r(f){for(var l="break,case,catch,continue,debugger,default,delete,do,else,finally,for,function,if,in,instanceof,new,return,switch,this,throw,try,typeof,var,void,while,with".split(","),k=[], +m=0;m":">"};p.prototype={computeProposals:function(h,l,k){for(var k=k.prefix,m=[],e=l-k.length-1,a="";e>=0;)if(a=h[e],a==="\n"||a==="\r")break;else if(/\s/.test(a))e--;else break;if(f[a])return m;m=m.concat(s(k,h,l));return m=m.concat(r(k,h,l))}};return{JSTemplateContentAssistProvider:p}}); +define("orion/editor/AsyncStyler",["i18n!orion/editor/nls/messages","orion/editor/annotations"],function(s,r){function p(f){return f.getProperty("objectClass").indexOf(h)!==-1&&f.getProperty("type")==="highlighter"}function f(f,h,e){this.initialize(f,h,e);this.lineStyles=[]}var h="orion.edit.highlighter",l=h+" service must be an event emitter";r.AnnotationType.registerType("orion.annotation.highlightError",{title:s.syntaxError,html:"
",rangeStyle:{styleClass:"annotationRange error"}}); +f.prototype={initialize:function(f,l,e){this.textView=f;this.serviceRegistry=l;this.annotationModel=e;this.services=[];var a=this;this.listener={onModelChanging:function(b){a.onModelChanging(b)},onModelChanged:function(b){a.onModelChanged(b)},onDestroy:function(b){a.onDestroy(b)},onLineStyle:function(b){a.onLineStyle(b)},onStyleReady:function(b){a.onStyleReady(b)},onServiceAdded:function(b){a.onServiceAdded(b.serviceReference,a.serviceRegistry.getService(b.serviceReference))},onServiceRemoved:function(b){a.onServiceRemoved(b.serviceReference, +a.serviceRegistry.getService(b.serviceReference))}};f.addEventListener("ModelChanging",this.listener.onModelChanging);f.addEventListener("ModelChanged",this.listener.onModelChanged);f.addEventListener("Destroy",this.listener.onDestroy);f.addEventListener("LineStyle",this.listener.onLineStyle);l.addEventListener("registered",this.listener.onServiceAdded);l.addEventListener("unregistering",this.listener.onServiceRemoved);f=l.getServiceReferences(h);for(e=0;e=this.string.length},sol:function(){return this.pos===0},peek:function(){return this.string[this.pos]},next:function(){return this.string[this.pos++]},eat:function(e){var a=this.string[this.pos];return typeof a==="string"&&(a===e||e.test&&e.test(a)||typeof e==="function"&& +e(a))?this.string[this.pos++]:void 0},eatWhile:function(e){for(var a=!1;this.eat(e)!==void 0;)a=!0;return a},eatSpace:function(){return this.eatWhile(/\s/)},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){e=this.string.indexOf(e,this.pos);return e!==-1?(this.pos=e,!0):!1},match:function(e,a,b){a=a===!0||typeof a==="undefined";if(typeof e==="string"){var d=b?this.string.toLowerCase():this.string,e=b?e.toLowerCase():e,b=d.indexOf(e,this.pos);if(b!==-1&&a)this.pos=b+e.length;return b!== +-1}else return(e=this.string.substring(this.pos).match(e))&&a&&typeof e[0]==="string"&&(this.pos+=e.index+e[0].length),e},backUp:function(e){this.pos-=e},column:function(){for(var e=0,a=0;a=b)break;this._expandRange(d,d);for(var f=this._getResumeLineIndex(d),d=f+1,f=(f=f>= +0&&this.lines[f].eolState)?this.codeMirror.copyState(this.mode,f):this.mode.startState(),g=0,h=d;h3;if(c||l)break;else if(!j||k)g=0;j=he&&j){this.highlightLater(h+1);this.onHighlightDone();return}}}this.onHighlightDone()},onHighlightDone:function(){this.startLine!==Number.MAX_VALUE&& +this.endLine!==-1&&this.dispatchEvent({type:"Highlight",start:this.startLine,end:this.endLine});this.startLine=Number.MAX_VALUE;this.endLine=-1},_getResumeLineIndex:function(e){for(var a=this.lines,b=e-1;b>=0;b--)if(a[b].eolState||e-b>40)return b;return-1},getState:function(e){var a=this.mode,b=this.lines,d,f;for(d=e-1;d>=0;d--)if(f=b[d],f.eolState||e-d>40)break;var g=d>=0&&b[d].eolState;if(g){g=this.codeMirror.copyState(a,g);for(d=Math.max(0,d);d
", +rangeStyle:{styleClass:"annotationRange error"}});m.prototype={init:function(e,a,b){this.textView=e;this.annotationModel=b;this.modeApplier=new k(e.getModel(),a);var d=this;this.listener={onLineStyle:function(a){d.onLineStyle(a)},onDestroy:function(a){d.onDestroy(a)},onHighlight:function(a){d.onHighlight(a)}};e.addEventListener("LineStyle",this.listener.onLineStyle);e.addEventListener("Destroy",this.listener.onDestroy);this.modeApplier.addEventListener("Highlight",this.listener.onHighlight)},destroy:function(){this.modeApplier&& +(this.modeApplier.removeEventListener("Highlight",this.listener.onHighlight),this.modeApplier.destroy());this.textView&&(this.textView.removeEventListener("LineStyle",this.listener.onLineStyle),this.textView.removeEventListener("Destroy",this.listener.onDestroy));this.listener=this.modeApplier=this.annotationModel=this.textView=null},setMode:function(e){this.modeApplier.setMode(e)},onLineStyle:function(e){var a=e.lineIndex,b=this.modeApplier,d=b.getLineStyle(a);if(!d||!d.eolState){var f=this.textView.getModel().getLineCount(); +b.highlight(a,Math.min(a+20,f-1),!0);d=b.getLineStyle(a)}f=this.textView.getModel();if(d){var g=b.toStyleRangesAndErrors(d,a);if(g&&(e.ranges=g[0],e=this.annotationModel)){b=[];d=[];if(g=g[1])for(var h=0;h/,func:function(){return"atomic group"}}],toRegExp:function(e){function a(a,b){throw Error('Unsupported regex feature "'+a+'": "'+b[0]+'" at index: '+b.index+" in "+b.input);}var b="",d,e=m.processGlobalFlag("x",e,function(a){for(var b="",c=!1,d=a.length,e=0;e=0;t--);v=b.charAt(t-1);s=t-1;D=b.substring(t,p+1)}t=h[h.length-1];if(v===")"&&(t.type===2||t.type===4)){k.splice(t.start,0,"(");k.push(D);k.push(")");r={start:t.start,end:k.length-1,type:4,num:t.num};for(v=0;v=t.start&&n.end<=s)if(n.start+=1,n.end+=1,n.num+=1,n.type===2)l[n.oldNum]=n.num;h.push(r);j++;break}default:r!=="|"&&n!==2&&n!==4&&g===0&&(f.push(4),h.push({start:p,end:-1,type:4,num:j}),k.push("("),m[j]=null,j++),k.push(r),r==="\\"&&(r=b.charAt(p+1),k.push(r),p+=1)}}for(;f.length;)f.pop(),k.push(")");var b=RegExp(k.join("")),d={},a=a||l,z;for(z in a)a.hasOwnProperty(z)&&(d[z]="\\"+a[z]);b=this.getSubstitutedRegex(b,d,!1);return[b,l,m]},complexCaptures:function(e){if(!e)return!1; +for(var a in e)if(e.hasOwnProperty(a)&&a!=="0")return!0;return!1}};l.prototype={initialize:function(e,a,b){this.textView=e;this.textView.stylerOptions=this;var d=this;this.textView&&a&&a.startup().then(function(a){k=a.preferences;d.preferences=k;d._updateStylesheet(k,b);d.storageKey=k.listenForChangedSettings(d._listener.onStorage)});this._listener={onModelChanged:function(a){d.onModelChanged(a)},onDestroy:function(a){d.onDestroy(a)},onLineStyle:function(a){d.onLineStyle(a)},onStorage:function(a){d.onStorage(a)}}; +e.addEventListener("ModelChanged",this._listener.onModelChanged);e.addEventListener("Destroy",this._listener.onDestroy);e.addEventListener("LineStyle",this._listener.onLineStyle);e.redrawLines()},onDestroy:function(){this.destroy()},onStorage:function(e){e.key===this.storageKey&&this._updateStylesheet(this.preferences)},destroy:function(){if(this.textView)this.textView.removeEventListener("ModelChanged",this._listener.onModelChanged),this.textView.removeEventListener("Destroy",this._listener.onDestroy), +this.textView.removeEventListener("LineStyle",this._listener.onLineStyle),this.textView=null;this._listener=this._tree=this._styles=this.grammar=null},preprocess:function(e){for(e=[e];e.length!==0;){var a=e.pop();if(!a._resolvedRule||!a._typedRule)if(a._resolvedRule=this._resolve(a),a._typedRule=this._createTypedRule(a),this.addStyles(a.name),this.addStyles(a.contentName),this.addStylesForCaptures(a.captures),this.addStylesForCaptures(a.beginCaptures),this.addStylesForCaptures(a.endCaptures),a._resolvedRule!== +a&&e.push(a._resolvedRule),a.patterns)for(var b=0;b0;)e.push(a[--b])},exec:function(e,a,b){(a=e.exec(a))&&(a.index+=b);e.lastIndex=0;return a},afterMatch:function(e){return e.index+e[0].length},getEndMatch:function(e,a,b){if(e instanceof this.BeginEndNode){var d=e.rule,e=e.endRegexSubstituted||d.endRegex;return!e?null:this.exec(e, +a,b)}return null},initialParse:function(){this.textView.getModel().getCharCount();this._tree=new this.ContainerNode(null,this.grammar._typedRule);this.parse(this._tree,!1,0)},onModelChanged:function(e){var a=e.addedCharCount,b=e.removedCharCount,e=e.start;if(this._tree){var d=this.textView.getModel(),f=d.getCharCount(),d=d.getLineEnd(d.getLineAtOffset(e)-1),g=this.getFirstDamaged(d,d),d=d===-1?0:d,a=g?this.parse(g,!0,d,e,a,b):f;this.textView.redrawRange(d,a)}else this.initialParse()},getFirstDamaged:function(e, +a){if(e<0)return this._tree;for(var b=[this._tree],d=null;b.length;){var f=b.pop();if(!f.parent||this.isDamaged(f,e,a)){f instanceof this.BeginEndNode&&(d=f);for(var g=0;ga},parse:function(e,a,b,d,f,g){var h=this.textView.getModel(),c=h.getLineStart(h.getLineCount()-1),j=h.getCharCount(),k=this.getInitialExpected(e,b),l=-1;if(a)e.repaired=!0,e.endNeedsUpdate=!0,l=(l=e.children[e.children.length- +1])?h.getLineEnd(h.getLineAtOffset(l.end+(f-g))):-1,d=h.getLineEnd(h.getLineAtOffset(d+g)),l=Math.max(l,d);for(var l=l===-1?j:l,d=k,m=e,p=!1,n=b,r=-1;m&&(!a||n=c?j:h.getLineStart(h.getLineAtOffset(n)+1));var t=s&&s.match,D=s&&s.rule,v=s&&s.isEnd;if(s&&s.isSub){if(n=this.afterMatch(t),D instanceof this.BeginEndRule)p=!0,a&&D===d.rule&&m===d.parent?(m=d,m.setStart(t),m.repaired=!0,m.endNeedsUpdate=!0,d=this.getNextExpected(d,"begin")):(a&&(this.prune(m,d), +a=!1),t=new this.BeginEndNode(m,D,t),m.addChild(t),m=t)}else if(v||n===j){if(m instanceof this.BeginEndNode)t?(p=!0,r=Math.max(r,m.end),m.setEnd(t),n=this.afterMatch(t),a&&m===d&&m.parent===d.parent?(m.repaired=!0,delete m.endNeedsUpdate,d=this.getNextExpected(d,"end")):a&&(this.prune(m,d),a=!1)):(m.setEnd(j),delete m.endNeedsUpdate);m=m.parent}a&&n>=l&&!p&&(this.prune(e,k),a=!1)}this.removeUnrepairedChildren(e,a,b);this.cleanup(a,e,b,l,j,f,g);return a?Math.max(r,n):n},removeUnrepairedChildren:function(e, +a,b){if(a){for(var a=e.children,d=-1,f=0;f=a)return d}else if(e instanceof this.BeginEndNode&&e.endMatch){var f=e.endMatch.index;for(b=0;b=a)break;if(d&&d.start< +f)return d}return e},getNextExpected:function(e,a){if(a==="begin"){var b=e.children[0];return b?b:e}else if(a==="end"&&(b=e.parent)){var d=b.children[b.children.indexOf(e)+1];return d?d:b}return null},prune:function(e,a){if(a.parent===e)e.children.length=a.getIndexInParent();else if(e instanceof this.BeginEndNode)e.endMatch=null,e.end=null;if(e.parent)e.parent.children.length=e.getIndexInParent()+1},onLineStyle:function(e){this._tree||this.initialParse();var a=e.lineStart,b=this.textView.getModel(), +d=b.getLineEnd(e.lineIndex),f=b.getLineEnd(b.getLineAtOffset(a)-1),f=this.getFirstDamaged(f,f),a=this.getLineScope(b,f,a,d);e.ranges=this.toStyleRanges(a);e.ranges.sort(function(a,b){return a.start-b.start})},getLineScope:function(e,a,b,d){for(var f=b,g=this.getInitialExpected(a,b),h=[],c=[];a&&f",contentName:"entity.name.tag.doctype.html",beginCaptures:{0:{name:"entity.name.tag.doctype.html"}},endCaptures:{0:{name:"entity.name.tag.doctype.html"}}},{begin:"<\!--",end:"--\>",beginCaptures:{0:{name:"punctuation.definition.comment.html"}},endCaptures:{0:{name:"punctuation.definition.comment.html"}}, +patterns:[{match:"--",name:"invalid.illegal.badcomment.html"}],contentName:"comment.block.html"},{match:"<[A-Za-z0-9_\\-:]+(?= ?)",name:"entity.name.tag.html"},{include:"#attrName"},{include:"#qString"},{include:"#qqString"},{include:"#entity"},{match:"",name:"entity.name.tag.html"},{match:">",name:"entity.name.tag.html"}],repository:{attrName:{match:"[A-Za-z\\-:]+(?=\\s*=\\s*['\"])",name:"entity.other.attribute.name.html"},qqString:{match:'(")[^"]+(")',name:"token.string"},qString:{match:"(')[^']+(')", +name:"token.string"},entity:{match:"&[A-Za-z0-9]+;",name:"constant.character.entity.html"}}}}}}); +define("examples/editor/textStyler",["orion/editor/annotations"],function(s){function r(a,b){this.keywords=a;this.whitespacesVisible=b;this.setText("")}function p(){r.call(this,null,!0)}function f(a){r.call(this,null,a)}function h(){r.call(this,null,!1)}function l(a,b,c){this.commentStart="/*";this.commentEnd="*/";var d=[];switch(b){case "java":d=m;break;case "js":d=k;break;case "css":d=e}this.whitespacesVisible=!1;this.detectHyperlinks=!0;this.highlightCaretLine=!1;this.detectTasks=this.foldingEnabled= +!0;this._scanner=new r(d,this.whitespacesVisible);this._firstScanner=new h;this._commentScanner=new f(this.whitespacesVisible);this._whitespaceScanner=new p;if(b==="css")this._scanner.isCSS=!0,this._firstScanner.isCSS=!0;this.view=a;this.annotationModel=c;this._bracketAnnotations=void 0;var g=this;this._listener={onChanged:function(a){g._onModelChanged(a)},onDestroy:function(a){g._onDestroy(a)},onLineStyle:function(a){g._onLineStyle(a)},onMouseDown:function(a){g._onMouseDown(a)},onSelection:function(a){g._onSelection(a)}}; +b=a.getModel();b.getBaseModel&&(b=b.getBaseModel());b.addEventListener("Changed",this._listener.onChanged);a.addEventListener("MouseDown",this._listener.onMouseDown);a.addEventListener("Selection",this._listener.onSelection);a.addEventListener("Destroy",this._listener.onDestroy);a.addEventListener("LineStyle",this._listener.onLineStyle);this._computeComments();this._computeFolding();a.redrawLines()}var k="break,case,class,catch,continue,const,debugger,default,delete,do,else,enum,export,extends,false,finally,for,function,if,implements,import,in,instanceof,interface,let,new,null,package,private,protected,public,return,static,super,switch,this,throw,true,try,typeof,undefined,var,void,while,with,yield".split(","), +m="abstract,boolean,break,byte,case,catch,char,class,continue,default,do,double,else,extends,false,final,finally,float,for,if,implements,import,instanceof,int,interface,long,native,new,null,package,private,protected,public,return,short,static,super,switch,synchronized,this,throw,throws,transient,true,try,void,volatile,while".split(","),e="alignment-adjust,alignment-baseline,animation,animation-delay,animation-direction,animation-duration,animation-iteration-count,animation-name,animation-play-state,animation-timing-function,appearance,azimuth,backface-visibility,background,background-attachment,background-clip,background-color,background-image,background-origin,background-position,background-repeat,background-size,baseline-shift,binding,bleed,bookmark-label,bookmark-level,bookmark-state,bookmark-target,border,border-bottom,border-bottom-color,border-bottom-left-radius,border-bottom-right-radius,border-bottom-style,border-bottom-width,border-collapse,border-color,border-image,border-image-outset,border-image-repeat,border-image-slice,border-image-source,border-image-width,border-left,border-left-color,border-left-style,border-left-width,border-radius,border-right,border-right-color,border-right-style,border-right-width,border-spacing,border-style,border-top,border-top-color,border-top-left-radius,border-top-right-radius,border-top-style,border-top-width,border-width,bottom,box-align,box-decoration-break,box-direction,box-flex,box-flex-group,box-lines,box-ordinal-group,box-orient,box-pack,box-shadow,box-sizing,break-after,break-before,break-inside,caption-side,clear,clip,color,color-profile,column-count,column-fill,column-gap,column-rule,column-rule-color,column-rule-style,column-rule-width,column-span,column-width,columns,content,counter-increment,counter-reset,crop,cue,cue-after,cue-before,cursor,direction,display,dominant-baseline,drop-initial-after-adjust,drop-initial-after-align,drop-initial-before-adjust,drop-initial-before-align,drop-initial-size,drop-initial-value,elevation,empty-cells,fit,fit-position,flex-align,flex-flow,flex-inline-pack,flex-order,flex-pack,float,float-offset,font,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,grid-columns,grid-rows,hanging-punctuation,height,hyphenate-after,hyphenate-before,hyphenate-character,hyphenate-lines,hyphenate-resource,hyphens,icon,image-orientation,image-rendering,image-resolution,inline-box-align,left,letter-spacing,line-height,line-stacking,line-stacking-ruby,line-stacking-shift,line-stacking-strategy,list-style,list-style-image,list-style-position,list-style-type,margin,margin-bottom,margin-left,margin-right,margin-top,mark,mark-after,mark-before,marker-offset,marks,marquee-direction,marquee-loop,marquee-play-count,marquee-speed,marquee-style,max-height,max-width,min-height,min-width,move-to,nav-down,nav-index,nav-left,nav-right,nav-up,opacity,orphans,outline,outline-color,outline-offset,outline-style,outline-width,overflow,overflow-style,overflow-x,overflow-y,padding,padding-bottom,padding-left,padding-right,padding-top,page,page-break-after,page-break-before,page-break-inside,page-policy,pause,pause-after,pause-before,perspective,perspective-origin,phonemes,pitch,pitch-range,play-during,position,presentation-level,punctuation-trim,quotes,rendering-intent,resize,rest,rest-after,rest-before,richness,right,rotation,rotation-point,ruby-align,ruby-overhang,ruby-position,ruby-span,size,speak,speak-header,speak-numeral,speak-punctuation,speech-rate,stress,string-set,table-layout,target,target-name,target-new,target-position,text-align,text-align-last,text-decoration,text-emphasis,text-height,text-indent,text-justify,text-outline,text-shadow,text-transform,text-wrap,top,transform,transform-origin,transform-style,transition,transition-delay,transition-duration,transition-property,transition-timing-function,unicode-bidi,vertical-align,visibility,voice-balance,voice-duration,voice-family,voice-pitch,voice-pitch-range,voice-rate,voice-stress,voice-volume,volume,white-space,white-space-collapse,widows,width,word-break,word-spacing,word-wrap,z-index".split(","), +a={styleClass:"comment"},b={styleClass:"token_multiline_comment"},d={styleClass:"token_doc_comment"},i={styleClass:"token_doc_html_markup"},g={styleClass:"token_task_tag"},o={styleClass:"token_doc_tag"},c={styleClass:"token-string"},j={styleClass:"token_number"},q={styleClass:"token_keyword"},u={styleClass:"token_space"},A={styleClass:"token_tab"},E={styleClass:"line_caret"};r.prototype={getOffset:function(){return this.offset},getStartOffset:function(){return this.startOffset},getData:function(){return this.text.substring(this.startOffset, +this.offset)},getDataLength:function(){return this.offset-this.startOffset},_default:function(a){switch(a){case 32:case 9:if(this.whitespacesVisible)return a===32?11:10;do a=this._read();while(a===32||a===9);this._unread(a);return 9;case 123:case 125:case 40:case 41:case 91:case 93:case 60:case 62:return a;default:var b=this.isCSS,c=this.offset-1;if(!b&&48<=a&&a<=57){var d=b=!1,e=!1,f=a;do if(a=this._read(),a===46&&!b)b=!0;else if(a===101&&!d)b=d=!0,a=this._read(),a!==45&&this._unread(a);else if(a=== +120&&f===48&&this.offset-c===2)b=d=e=!0;else if(!(48<=a&&a<=57||e&&(65<=a&&a<=70||97<=a&&a<=102)))break;while(1);this._unread(a);return 3}if(97<=a&&a<=122||65<=a&&a<=90||a===95||45===a&&b){do a=this._read();while(97<=a&&a<=122||65<=a&&a<=90||a===95||48<=a&&a<=57||45===a&&b);this._unread(a);a=this.keywords;if(a.length>0){c=this.text.substring(c,this.offset);for(b=0;b1;)if(f=Math.floor((e+d)/2),b<=a[f].start)e=f;else if(c&&b=g)break;var l= +j[k].start,m=j[k].end;i0){for(var e=a,g=f;g>0;){f=e.charCodeAt(g-1);if(!(97<=f&&f<=122||65<=f&&f<=90||45===f||48<=f&&f<=57))break;g--}if(g>0&&(f="\"\"''(){}[]<>".indexOf(e.substring(g- +1,g)),f!==-1&&(f&1)===0&&(f=e.lastIndexOf("\"\"''(){}[]<>".substring(f+1,f+2)))!==-1)){var h=f;f=this._clone(d);f.tagName="A";f.attributes={href:e.substring(g,h)};c.push({start:b,end:b+g,style:d});c.push({start:b+g,end:b+h,style:f});c.push({start:b+h,end:b+a.length,style:d});return null}}else a.toLowerCase().indexOf("bug#")===0&&(e="https://bugs.eclipse.org/bugs/show_bug.cgi?id="+parseInt(a.substring(4),10));return e?(f=this._clone(d),f.tagName="A",f.attributes={href:e},f):d},_clone:function(a){if(!a)return a; +var b={},c;for(c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b},_findComments:function(a,b){var b=b||0,c=this._firstScanner,d;c.setText(a);for(var e=[];d=c.nextToken();)(d===7||d===8||d===5)&&e.push({start:c.getStartOffset()+b,end:c.getOffset()+b,type:d}),(d===6||d===7||d===8)&&this._computeTasks(d,c.getStartOffset()+b,c.getOffset()+b);return e},_findMatchingBracket:function(a,b){var c="{}()[]<>",d=a.getText(b,b+1),e=c.indexOf(d,0);if(e===-1)return-1;var f;f=e&1?c.substring(e-1,e):c.substring(e+ +1,e+2);for(var g=a.getLineAtOffset(b),c=a.getLine(g),h=a.getLineStart(g),i=a.getLineEnd(g),c=this._findBrackets(d,f,c,h,h,i),i=0;i=0?1:-1,c[i]*h-1===b){var j=1;if(e&1){for(i--;i>=0;i--)if(h=c[i]>=0?1:-1,j+=h,j===0)return c[i]*h-1;for(g-=1;g>=0;){c=a.getLine(g);h=a.getLineStart(g);i=a.getLineEnd(g);c=this._findBrackets(d,f,c,h,h,i);for(e=c.length-1;e>=0;e--)if(h=c[e]>=0?1:-1,j+=h,j===0)return c[e]*h-1;g--}}else{for(i++;i=0?1:-1,j+=h,j===0)return c[i]* +h-1;g+=1;for(e=a.getLineCount();g=0?1:-1,j+=h,j===0)return c[i]*h-1;g++}}break}return-1},_findBrackets:function(a,b,c,d,e,f){for(var g=[],a=a.charCodeAt(0),b=b.charCodeAt(0),h=e,i=this._scanner,j,k=this.comments,l=this._binarySearch(k,e,!0);l=f)break;j=k[l].start;var m=k[l].end;if(h0)i-=1,a.getBaseModel&&(i=a.mapOffset(i),a=a.getBaseModel()),a=this._findMatchingBracket(a,i),a!==-1&&(h=[s.AnnotationType.createAnnotation(s.AnnotationType.ANNOTATION_MATCHING_BRACKET,a,a+1),s.AnnotationType.createAnnotation(s.AnnotationType.ANNOTATION_CURRENT_BRACKET, +i,i+1)]);this._bracketAnnotations=h;this.annotationModel.replaceAnnotations(b,h)}},_onMouseDown:function(a){if(a.clickCount===2){var b=this.view,c=b.getModel(),d=b.getOffsetAtLocation(a.x,a.y);if(d>0){var e=d-1,f=c;c.getBaseModel&&(e=c.mapOffset(e),f=c.getBaseModel());e=this._findMatchingBracket(f,e);e!==-1&&(a.preventDefault(),a=e,c.getBaseModel&&(a=c.mapOffset(a,!0)),d>a&&(d--,a++),b.setSelection(a,d))}}},_onModelChanged:function(a){var b=a.start,c=a.removedCharCount,d=a.addedCharCount-c,e=this.view, +a=e.getModel(),f=a.getBaseModel?a.getBaseModel():a,c=b+c,g=f.getCharCount(),h=this.comments.length,i=f.getLineStart(f.getLineAtOffset(b)),j=this._binarySearch(this.comments,i,!0),k=this._binarySearch(this.comments,c,!1,j-1,h);jb&&(i+=d)):i=j===h&&h>0&&g-d===this.comments[h-1].end?this.comments[h-1].start:i;var l;kb&&(l+=d),k+=1):(k=h,l=g);for(var m,g=this._findComments(f.getText(i,l),i), +h=j;hb&&(m.start+=d),m.start>b&&(m.end+=d);var o=k-j!==g.length;if(!o)for(h=0;hb&&(h-=d),k>b&&(k-=d),h<=b&&b + + 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 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 plusplus:true */ +/*global doctrine:true, exports:true, parseTypeExpression:true, parseTop:true*/ + +(function (exports) { + 'use strict'; + + var VERSION, + Regex, + CanAccessStringByIndex, + typed, + jsdoc, + isArray; + + // Sync with package.json. + VERSION = '0.0.4-dev'; + + // See also tools/generate-unicode-regex.py. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), + NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') + }; + + CanAccessStringByIndex = typeof 'doctrine'[0] !== undefined; + + function sliceSource(source, index, last) { + return source.slice(index, last); + } + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(ary) { + return Object.prototype.toString.call(ary) === '[object Array]'; + }; + } + + if (!CanAccessStringByIndex) { + sliceSource = function sliceSource(source, index, last) { + return source.slice(index, last).join(''); + }; + } + + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + + function isLineTerminator(ch) { + return ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029'; + } + + function isWhiteSpace(ch) { + return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') || + (ch === '\u000C') || (ch === '\u00A0') || + (ch.charCodeAt(0) >= 0x1680 && + '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0); + } + + function isDecimalDigit(ch) { + return '0123456789'.indexOf(ch) >= 0; + } + + function isHexDigit(ch) { + return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; + } + + function isOctalDigit(ch) { + return '01234567'.indexOf(ch) >= 0; + } + + function isASCIIAlphanumeric(ch) { + return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'); + } + + function isIdentifierStart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch)); + } + + function isIdentifierPart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch >= '0') && (ch <= '9')) || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch)); + } + + function isTypeName(ch) { + return '><(){}[],:*|?!='.indexOf(ch) === -1 && !isWhiteSpace(ch) && !isLineTerminator(ch); + } + + function assert(cond, text) { } + + if (VERSION.slice(-3) === 'dev') { + assert = function assert(cond, text) { + if (!cond) { + throw new Error(text); + } + }; + } + + function trim(str) { + return str.replace(/^\s+/, '').replace(/\s+$/, ''); + } + + function unwrapComment(doc) { + // JSDoc comment is following form + // /** + // * ....... + // */ + // remove /**, */ and * + var BEFORE_STAR = 0, + STAR = 1, + AFTER_STAR = 2, + index, + len, + mode, + result, + ch; + + doc = doc.replace(/^\/\*\*/, '').replace(/\*\/$/, ''); + index = 0; + len = doc.length; + mode = BEFORE_STAR; + result = ''; + + while (index < len) { + ch = doc[index]; + switch (mode) { + case BEFORE_STAR: + if (isLineTerminator(ch)) { + result += ch; + } else if (ch === '*') { + mode = STAR; + } else if (!isWhiteSpace(ch)) { + result += ch; + mode = AFTER_STAR; + } + break; + + case STAR: + if (!isWhiteSpace(ch)) { + result += ch; + } + mode = AFTER_STAR; + break; + + case AFTER_STAR: + result += ch; + if (isLineTerminator(ch)) { + mode = BEFORE_STAR; + } + break; + } + index += 1; + } + + return result; + } + + // Type Expression Parser + + (function (exports) { + var Syntax, + Token, + index, + previous, + source, + length, + token, + value; + + Syntax = { + NullableLiteral: 'NullableLiteral', + AllLiteral: 'AllLiteral', + NullLiteral: 'NullLiteral', + UndefinedLiteral: 'UndefinedLiteral', + VoidLiteral: 'VoidLiteral', + UnionType: 'UnionType', + ArrayType: 'ArrayType', + RecordType: 'RecordType', + FieldType: 'FieldType', + FunctionType: 'FunctionType', + ParameterType: 'ParameterType', + RestType: 'RestType', + NonNullableType: 'NonNullableType', + OptionalType: 'OptionalType', + NullableType: 'NullableType', + NameExpression: 'NameExpression', + TypeApplication: 'TypeApplication' + }; + + Token = { + ILLEGAL: 0, // ILLEGAL + DOT: 1, // . + DOT_LT: 2, // .< + REST: 3, // ... + LT: 4, // < + GT: 5, // > + LPAREN: 6, // ( + RPAREN: 7, // ) + LBRACE: 8, // { + RBRACE: 9, // } + LBRACK: 10, // [ + RBRACK: 11, // ] + COMMA: 12, // , + COLON: 13, // : + STAR: 14, // * + PIPE: 15, // | + QUESTION: 16, // ? + BANG: 17, // ! + EQUAL: 18, // = + NAME: 19, // name token + STRING: 20, // string + NUMBER: 21, // number + EOF: 22 + }; + + function advance() { + var ch = source[index]; + index += 1; + return ch; + } + + function scanHexEscape(prefix) { + var i, len, ch, code = 0; + + len = (prefix === 'u') ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && isHexDigit(source[index])) { + ch = advance(); + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } + + function scanString() { + var str = '', quote, ch, code, unescaped, restore, octal = false; + quote = source[index]; + ++index; + + while (index < length) { + ch = advance(); + + if (ch === quote) { + quote = ''; + break; + } else if (ch === '\\') { + ch = advance(); + if (!isLineTerminator(ch)) { + switch (ch) { + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'u': + case 'x': + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + str += unescaped; + } else { + index = restore; + str += ch; + } + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\v'; + break; + + default: + if (isOctalDigit(ch)) { + code = '01234567'.indexOf(ch); + + // \0 is not octal escape sequence + if (code !== 0) { + octal = true; + } + + if (index < length && isOctalDigit(source[index])) { + octal = true; + code = code * 8 + '01234567'.indexOf(advance()); + + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && + index < length && + isOctalDigit(source[index])) { + code = code * 8 + '01234567'.indexOf(advance()); + } + } + str += String.fromCharCode(code); + } else { + str += ch; + } + break; + } + } else { + if (ch === '\r' && source[index] === '\n') { + ++index; + } + } + } else if (isLineTerminator(ch)) { + break; + } else { + str += ch; + } + } + + if (quote !== '') { + throw 'unexpected quote'; + } + + value = str; + return Token.STRING; + } + + function scanNumber() { + var number, ch; + + number = ''; + if (ch !== '.') { + number = advance(); + ch = source[index]; + + if (number === '0') { + if (ch === 'x' || ch === 'X') { + number += advance(); + while (index < length) { + ch = source[index]; + if (!isHexDigit(ch)) { + break; + } + number += advance(); + } + + if (number.length <= 2) { + // only 0x + throw 'unexpected token'; + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch)) { + throw 'unexpected token'; + } + } + value = parseInt(number, 16); + return Token.NUMBER; + } + + if (isOctalDigit(ch)) { + number += advance(); + while (index < length) { + ch = source[index]; + if (!isOctalDigit(ch)) { + break; + } + number += advance(); + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch) || isDecimalDigit(ch)) { + throw 'unexpected token'; + } + } + value = parseInt(number, 8); + return Token.NUMBER; + } + + if (isDecimalDigit(ch)) { + throw 'unexpected token'; + } + } + + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } + + if (ch === '.') { + number += advance(); + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } + + if (ch === 'e' || ch === 'E') { + number += advance(); + + ch = source[index]; + if (ch === '+' || ch === '-') { + number += advance(); + } + + ch = source[index]; + if (isDecimalDigit(ch)) { + number += advance(); + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } else { + throw 'unexpected token'; + } + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch)) { + throw 'unexpected token'; + } + } + + value = parseFloat(number); + return Token.NUMBER; + } + + + function scanTypeName() { + var ch, ch2; + + value = advance(); + while (index < length && isTypeName(source[index])) { + ch = source[index]; + if (ch === '.') { + if ((index + 1) < length) { + ch2 = source[index + 1]; + if (ch2 === '<') { + break; + } + } + } + value += advance(); + } + return Token.NAME; + } + + function next() { + var ch; + + previous = index; + + while (index < length && isWhiteSpace(source[index])) { + advance(); + } + if (index >= length) { + token = Token.EOF; + return token; + } + + ch = source[index]; + switch (ch) { + case '"': + token = scanString(); + return token; + + case ':': + advance(); + token = Token.COLON; + return token; + + case ',': + advance(); + token = Token.COMMA; + return token; + + case '(': + advance(); + token = Token.LPAREN; + return token; + + case ')': + advance(); + token = Token.RPAREN; + return token; + + case '[': + advance(); + token = Token.LBRACK; + return token; + + case ']': + advance(); + token = Token.RBRACK; + return token; + + case '{': + advance(); + token = Token.LBRACE; + return token; + + case '}': + advance(); + token = Token.RBRACE; + return token; + + case '.': + advance(); + if (index < length) { + ch = source[index]; + if (ch === '<') { + advance(); + token = Token.DOT_LT; + return token; + } + + if (ch === '.' && index + 1 < length && source[index + 1] === '.') { + advance(); + advance(); + token = Token.REST; + return token; + } + + if (isDecimalDigit(ch)) { + token = scanNumber(); + return token; + } + } + token = Token.DOT; + return token; + + case '<': + advance(); + token = Token.LT; + return token; + + case '>': + advance(); + token = Token.GT; + return token; + + case '*': + advance(); + token = Token.STAR; + return token; + + case '|': + advance(); + token = Token.PIPE; + return token; + + case '?': + advance(); + token = Token.QUESTION; + return token; + + case '!': + advance(); + token = Token.BANG; + return token; + + case '=': + advance(); + token = Token.EQUAL; + return token; + + default: + if (isDecimalDigit(ch)) { + token = scanNumber(); + return token; + } + + // type string permits following case, + // + // namespace.module.MyClass + // + // this reduced 1 token TK_NAME + if (isTypeName(ch)) { + token = scanTypeName(); + return token; + } + + token = Token.ILLEGAL; + return token; + } + } + + function consume(target, text) { + assert(token === target, text || 'consumed token not matched'); + next(); + } + + function expect(target) { + if (token !== target) { + throw 'unexpected token'; + } + next(); + } + + // UnionType := '(' TypeUnionList ')' + // + // TypeUnionList := + // <> + // | NonemptyTypeUnionList + // + // NonemptyTypeUnionList := + // TypeExpression + // | TypeExpression '|' NonemptyTypeUnionList + function parseUnionType() { + var elements; + consume(Token.LPAREN, 'UnionType should start with ('); + elements = []; + if (token !== Token.RPAREN) { + while (true) { + elements.push(parseTypeExpression()); + if (token === Token.RPAREN) { + break; + } + expect(Token.PIPE); + } + } + consume(Token.RPAREN, 'UnionType should end with )'); + return { + type: Syntax.UnionType, + elements: elements + }; + } + + // ArrayType := '[' ElementTypeList ']' + // + // ElementTypeList := + // <> + // | TypeExpression + // | '...' TypeExpression + // | TypeExpression ',' ElementTypeList + function parseArrayType() { + var elements; + consume(Token.LBRACK, 'ArrayType should start with ['); + elements = []; + while (token !== Token.RBRACK) { + if (token === Token.REST) { + consume(Token.REST); + elements.push({ + type: Syntax.RestType, + expression: parseTypeExpression() + }); + break; + } else { + elements.push(parseTypeExpression()); + } + if (token !== Token.RBRACK) { + expect(Token.COMMA); + } + } + expect(Token.RBRACK); + return { + type: Syntax.ArrayType, + elements: elements + }; + } + + function parseFieldName() { + var v = value; + if (token === Token.NAME || token === Token.STRING) { + next(); + return v; + } + + if (token === Token.NUMBER) { + consume(Token.NUMBER); + return String(v); + } + + throw 'unexpected token'; + } + + // FieldType := + // FieldName + // | FieldName ':' TypeExpression + // + // FieldName := + // NameExpression + // | StringLiteral + // | NumberLiteral + // | ReservedIdentifier + function parseFieldType() { + var key; + + key = parseFieldName(); + if (token === Token.COLON) { + consume(Token.COLON); + return { + type: Syntax.FieldType, + key: key, + value: parseTypeExpression() + }; + } + return { + type: Syntax.FieldType, + key: key, + value: null + }; + } + + // RecordType := '{' FieldTypeList '}' + // + // FieldTypeList := + // <> + // | FieldType + // | FieldType ',' FieldTypeList + function parseRecordType() { + var fields, field; + + consume(Token.LBRACE, 'RecordType should start with {'); + fields = []; + if (token === Token.COMMA) { + consume(Token.COMMA); + } else { + while (token !== Token.RBRACE) { + fields.push(parseFieldType()); + if (token !== Token.RBRACE) { + expect(Token.COMMA); + } + } + } + expect(Token.RBRACE); + return { + type: Syntax.RecordType, + fields: fields + }; + } + + function parseNameExpression() { + var name = value; + expect(Token.NAME); + return { + type: Syntax.NameExpression, + name: name + }; + } + + // TypeExpressionList := + // TopLevelTypeExpression + // | TopLevelTypeExpression ',' TypeExpressionList + function parseTypeExpressionList() { + var elements = []; + + elements.push(parseTop()); + while (token === Token.COMMA) { + consume(Token.COMMA); + elements.push(parseTop()); + } + return elements; + } + + // TypeName := + // NameExpression + // | NameExpression TypeApplication + // + // TypeApplication := + // '.<' TypeExpressionList '>' + // | '<' TypeExpressionList '>' // this is extension of doctrine + function parseTypeName() { + var expr, applications; + + expr = parseNameExpression(); + if (token === Token.DOT_LT || token === Token.LT) { + next(); + applications = parseTypeExpressionList(); + expect(Token.GT); + return { + type: Syntax.TypeApplication, + expression: expr, + applications: applications + }; + } + return expr; + } + + // ResultType := + // <> + // | ':' void + // | ':' TypeExpression + // + // BNF is above + // but, we remove <> pattern, so token is always TypeToken::COLON + function parseResultType() { + consume(Token.COLON, 'ResultType should start with :'); + if (token === Token.NAME && value === 'void') { + consume(Token.NAME); + return { + type: Syntax.VoidLiteral + }; + } + return parseTypeExpression(); + } + + // ParametersType := + // RestParameterType + // | NonRestParametersType + // | NonRestParametersType ',' RestParameterType + // + // RestParameterType := + // '...' + // '...' Identifier + // + // NonRestParametersType := + // ParameterType ',' NonRestParametersType + // | ParameterType + // | OptionalParametersType + // + // OptionalParametersType := + // OptionalParameterType + // | OptionalParameterType, OptionalParametersType + // + // OptionalParameterType := ParameterType= + // + // ParameterType := TypeExpression | Identifier ':' TypeExpression + // + // Identifier is "new" or "this" + function parseParametersType() { + var params = [], normal = true, expr; + + while (token !== Token.RPAREN) { + if (token === Token.REST) { + // RestParameterType + consume(Token.REST); + expr = null; + if (token !== Token.RPAREN) { + expr = parseNameExpression(); + } + params.push({ + type: Syntax.RestType, + expression: expr + }); + break; + } + + expr = parseTypeExpression(); + if (expr.type === Syntax.NameExpression && token === Token.COLON) { + // Identifier ':' TypeExpression + consume(Token.COLON); + expr = { + type: Syntax.ParameterType, + name: expr.name, + expression: parseTypeExpression() + }; + } + if (token === Token.EQUAL) { + consume(Token.EQUAL); + expr = { + type: Syntax.OptionalType, + expression: expr + }; + normal = false; + } else { + if (!normal) { + throw 'unexpected token'; + } + } + params.push(expr); + if (token !== Token.RPAREN) { + expect(Token.COMMA); + } + } + return params; + } + + // FunctionType := 'function' FunctionSignatureType + // + // FunctionSignatureType := + // | TypeParameters '(' ')' ResultType + // | TypeParameters '(' ParametersType ')' ResultType + // | TypeParameters '(' 'this' ':' TypeName ')' ResultType + // | TypeParameters '(' 'this' ':' TypeName ',' ParametersType ')' ResultType + function parseFunctionType() { + var isNew, thisBinding, params, result; + assert(token === Token.NAME && value === 'function', 'FunctionType should start with \'function\''); + consume(Token.NAME); + + // Google Closure Compiler is not implementing TypeParameters. + // So we do not. if we don't get '(', we see it as error. + expect(Token.LPAREN); + + isNew = false; + params = []; + thisBinding = null; + + if (token !== Token.RPAREN) { + // ParametersType or 'this' + if (token === Token.NAME && + (value === 'this' || value === 'new')) { + // 'this' or 'new' + // 'new' is Closure Compiler extension + isNew = value === 'new'; + consume(Token.NAME); + expect(Token.COLON); + thisBinding = parseTypeName(); + if (token === Token.COMMA) { + consume(Token.COMMA); + params = parseParametersType(); + } + } else { + params = parseParametersType(); + } + } + + expect(Token.RPAREN); + + result = null; + if (token === Token.COLON) { + result = parseResultType(); + } + + return { + type: Syntax.FunctionType, + params: params, + result: result, + 'this': thisBinding, + 'new': isNew + }; + } + + // BasicTypeExpression := + // '*' + // | 'null' + // | 'undefined' + // | TypeName + // | FunctionType + // | UnionType + // | RecordType + // | ArrayType + function parseBasicTypeExpression() { + switch (token) { + case Token.STAR: + consume(Token.STAR); + return { + type: Syntax.AllLiteral + }; + + case Token.LPAREN: + return parseUnionType(); + + case Token.LBRACK: + return parseArrayType(); + + case Token.LBRACE: + return parseRecordType(); + + case Token.NAME: + if (value === 'null') { + consume(Token.NAME); + return { + type: Syntax.NullLiteral + }; + } + + if (value === 'undefined') { + consume(Token.NAME); + return { + type: Syntax.UndefinedLiteral + }; + } + + if (value === 'function') { + return parseFunctionType(); + } + + return parseTypeName(); + + default: + throw "unexpected token"; + } + } + + // TypeExpression := + // BasicTypeExpression + // | '?' BasicTypeExpression + // | '!' BasicTypeExpression + // | BasicTypeExpression '?' + // | BasicTypeExpression '!' + // | '?' + function parseTypeExpression() { + var expr; + + if (token === Token.QUESTION) { + consume(Token.QUESTION); + if (token === Token.COMMA || token === Token.EQUAL || token === Token.RBRACE || + token === Token.RPAREN || token === Token.PIPE || token === Token.EOF) { + return { + type: Syntax.NullableLiteral + }; + } + return { + type: Syntax.NullableType, + expression: parseBasicTypeExpression(), + prefix: true + }; + } + + if (token === Token.BANG) { + consume(Token.BANG); + return { + type: Syntax.NonNullableType, + expression: parseBasicTypeExpression(), + prefix: true + }; + } + + expr = parseBasicTypeExpression(); + if (token === Token.BANG) { + consume(Token.BANG); + return { + type: Syntax.NonNullableType, + expression: expr, + prefix: false + }; + } + + if (token === Token.QUESTION) { + consume(Token.QUESTION); + return { + type: Syntax.NullableType, + expression: expr, + prefix: false + }; + } + + return expr; + } + + // TopLevelTypeExpression := + // TypeExpression + // | TypeUnionList + // + // This rule is Google Closure Compiler extension, not ES4 + // like, + // { number | string } + // If strict to ES4, we should write it as + // { (number|string) } + function parseTop() { + var expr, elements; + + expr = parseTypeExpression(); + if (token !== Token.PIPE) { + return expr; + } + + elements = [ expr ]; + consume(Token.PIPE); + while (true) { + elements.push(parseTypeExpression()); + if (token !== Token.PIPE) { + break; + } + consume(Token.PIPE); + } + + return { + type: Syntax.UnionType, + elements: elements + }; + } + + function parseTopParamType() { + var expr; + + if (token === Token.REST) { + consume(Token.REST); + return { + type: Syntax.RestType, + expression: parseTop() + }; + } + + expr = parseTop(); + if (token === Token.EQUAL) { + consume(Token.EQUAL); + return { + type: Syntax.OptionalType, + expression: expr + }; + } + + return expr; + } + + function parseType(src, opt) { + var expr; + + source = src; + length = source.length; + index = 0; + previous = 0; + + if (!CanAccessStringByIndex) { + source = source.split(''); + } + + next(); + expr = parseTop(); + + if (opt && opt.midstream) { + return { + expression: expr, + index: previous + }; + } + + if (token !== Token.EOF) { + throw 'not reach to EOF'; + } + + return expr; + } + + function parseParamType(src, opt) { + var expr; + + source = src; + length = source.length; + index = 0; + previous = 0; + + if (!CanAccessStringByIndex) { + source = source.split(''); + } + + next(); + expr = parseTopParamType(); + + if (opt && opt.midstream) { + return { + expression: expr, + index: previous + }; + } + + if (token !== Token.EOF) { + throw 'not reach to EOF'; + } + + return expr; + } + + exports.parseType = parseType; + exports.parseParamType = parseParamType; + }(typed = {})); + + // JSDoc Tag Parser + + (function (exports) { + var index, + length, + source, + recoverable; + + function advance() { + var ch = source[index]; + index += 1; + return ch; + } + + function scanTitle() { + var title = ''; + // waste '@' + advance(); + + while (index < length && isASCIIAlphanumeric(source[index])) { + title += advance(); + } + + return title; + } + + function seekContent() { + var ch, waiting, last = index; + + waiting = false; + while (last < length) { + ch = source[last]; + if (isLineTerminator(ch)) { + waiting = true; + } else if (waiting) { + if (ch === '@') { + break; + } + if (!isWhiteSpace(ch)) { + waiting = false; + } + } + last += 1; + } + return last; + } + + // type expression may have nest brace, such as, + // { { ok: string } } + // + // therefore, scanning type expression with balancing braces. + function parseType(title, last) { + var ch, brace, type, direct = false, res; + + // search '{' + while (index < last) { + ch = source[index]; + if (isWhiteSpace(ch)) { + advance(); + } else if (ch === '{') { + advance(); + break; + } else { + // this is direct pattern + direct = true; + break; + } + } + + if (!direct) { + // type expression { is found + brace = 0; + type = ''; + while (index < last) { + ch = source[index]; + if (isLineTerminator(ch)) { + return; + } + if (ch === '}') { + if (brace === 0) { + advance(); + break; + } else { + brace -= 1; + } + } else if (ch === '{') { + brace += 1; + } + type += advance(); + } + + try { + if (title === 'param') { + return typed.parseParamType(type); + } + return typed.parseType(type); + } catch (e1) { + // parse failed + return; + } + } else { + type = sliceSource(source, index, last); + try { + if (title === 'param') { + res = typed.parseParamType(type, { midstream: true }); + } else { + res = typed.parseType(type, { midstream: true }); + } + index += res.index; + return res.expression; + } catch (e2) { + // parse failed + return; + } + } + } + + function parseName(last) { + var range, ch, name, i, len; + + // skip white spaces + while (index < last && (isWhiteSpace(source[index]) || isLineTerminator(source[index]))) { + advance(); + } + + if (index >= last) { + return; + } + + if (!isIdentifierStart(source[index])) { + return; + } + + name = advance(); + + while (index < last) { + ch = source[index]; + if (isWhiteSpace(ch) || isLineTerminator(ch)) { + advance(); + break; + } + if (!isIdentifierPart(ch)) { + return; + } + name += advance(); + } + + return name; + } + + function isTypeParameterRequired(title) { + return title === 'define' || title === 'enum' || title === 'extends' || + title === 'implements' || title === 'param' || title === 'return' || + title === 'this' || title === 'type' || title === 'typedef' || + title === 'throws' || title === 'returns' || title === 'property' || + title === 'augments'; + } + + function scanDescription() { + var description = ''; + while (index < length && source[index] != '@') { + description += advance(); + } + return description; + } + + function next() { + var tag, title, type, last, description; + + // skip to tag + while (index < length && source[index] !== '@') { + advance(); + } + if (index >= length) { + return; + } + + assert(source[index] === '@'); + + // scan title + title = scanTitle(); + + // empty title + if (!title && !recoverable) { + return; + } + + // seek to content last index + last = seekContent(title); + + tag = { + title: title, + description: null + }; + + // type required titles + if (isTypeParameterRequired(title)) { + tag.type = parseType(title, last); + if (!tag.type && !recoverable) { + return; + } + } + + // param, property requires name + if (title === 'param' || title === 'property') { + tag.name = parseName(last); + if (!tag.name && !recoverable) { + return; + } + } + + // slice description + description = trim(sliceSource(source, index, last)); + if (description) { + tag.description = description; + } + index = last; + return tag; + } + + function stringToArray(str) { + return str.split(''); + } + + function parse(comment, options) { + var tags = [], tag, description, interestingTags; + + if (options === undefined) { + options = {}; + } + + if (typeof options.unwrap === 'boolean' && options.unwrap) { + source = unwrapComment(comment); + } else { + source = comment; + } + + // array of relevant tags + if (options.tags) { + if (isArray(options.tags)) { + interestingTags = { }; + for (var i = 0; i < options.tags.length; i++) { + if (typeof options.tags[i] === 'string') { + interestingTags[options.tags[i]] = true; + } else { + throw new Error('Invalid "tags" parameter: ' + options.tags); + } + } + } else { + throw new Error('Invalid "tags" parameter: ' + options.tags); + } + } + + if (!CanAccessStringByIndex) { + source = source.split(''); + } + + length = source.length; + index = 0; + recoverable = options.recoverable; + + description = trim(scanDescription()); + + while (true) { + tag = next(); + if (!tag) { + break; + } + if (!interestingTags || interestingTags.hasOwnProperty(tag.title)) { + tags.push(tag); + } + } + + return { + description: description, + tags: tags + }; + } + + exports.parse = parse; + }(jsdoc = {})); + + exports.version = VERSION; + exports.parse = jsdoc.parse; + exports.parseType = typed.parseType; + exports.parseParamType = typed.parseParamType; + exports.unwrapComment = unwrapComment; + exports.Syntax = shallowCopy(typed.Syntax); +}(typeof exports === 'undefined' ? (doctrine = {}) : exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/scripts/lib/esprima-master/assets/orion/contentassist/esprima.js b/scripts/lib/esprima-master/assets/orion/contentassist/esprima.js new file mode 100755 index 0000000..18792b5 --- /dev/null +++ b/scripts/lib/esprima-master/assets/orion/contentassist/esprima.js @@ -0,0 +1,3773 @@ +/* + + Original copyright is below. This is version git tag: 310927be9f. + Further modifications: + Author: Andy Clement (VMware) - recovery support + + + Original copyright: + + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Mathias Bynens + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Kris Kowal + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + + 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 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 plusplus:true */ +/*global esprima:true, exports:true, +throwError: true, createLiteral: true, generateStatement: true, +parseAssignmentExpression: true, parseBlock: true, parseExpression: true, +parseFunctionDeclaration: true, parseFunctionExpression: true, +parseFunctionSourceElements: true, parseVariableIdentifier: true, +parseLeftHandSideExpression: true, +parseStatement: true, parseSourceElement: true */ + +(function (exports) { + 'use strict'; + + var Token, + TokenName, + Syntax, + PropertyKind, + Messages, + Regex, + source, + strict, + index, + lineNumber, + lineStart, + length, + buffer, + state, + extra; + + Token = { + BooleanLiteral: 1, + EOF: 2, + Identifier: 3, + Keyword: 4, + NullLiteral: 5, + NumericLiteral: 6, + Punctuator: 7, + StringLiteral: 8 + }; + + TokenName = {}; + TokenName[Token.BooleanLiteral] = 'Boolean'; + TokenName[Token.EOF] = ''; + TokenName[Token.Identifier] = 'Identifier'; + TokenName[Token.Keyword] = 'Keyword'; + TokenName[Token.NullLiteral] = 'Null'; + TokenName[Token.NumericLiteral] = 'Numeric'; + TokenName[Token.Punctuator] = 'Punctuator'; + TokenName[Token.StringLiteral] = 'String'; + + 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' + }; + + PropertyKind = { + Data: 1, + Get: 2, + Set: 4 + }; + + // Error messages should be identical to V8. + Messages = { + UnexpectedToken: 'Unexpected token %0', + UnexpectedNumber: 'Unexpected number', + UnexpectedString: 'Unexpected string', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedEOS: 'Unexpected end of input', + NewlineAfterThrow: 'Illegal newline after throw', + InvalidRegExp: 'Invalid regular expression', + UnterminatedRegExp: 'Invalid regular expression: missing /', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + NoCatchOrFinally: 'Missing catch or finally after try', + UnknownLabel: 'Undefined label \'%0\'', + Redeclaration: '%0 \'%1\' has already been declared', + IllegalContinue: 'Illegal continue statement', + IllegalBreak: 'Illegal break statement', + IllegalReturn: 'Illegal return statement', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', + AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', + AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode' + }; + + // See also tools/generate-unicode-regex.py. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), + NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') + }; + + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + + function assert(condition, message) { + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + + function sliceSource(from, to) { + return source.slice(from, to); + } + + if (typeof 'esprima'[0] === 'undefined') { + sliceSource = function sliceArraySource(from, to) { + return source.slice(from, to).join(''); + }; + } + + function isDecimalDigit(ch) { + return '0123456789'.indexOf(ch) >= 0; + } + + function isHexDigit(ch) { + return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; + } + + function isOctalDigit(ch) { + return '01234567'.indexOf(ch) >= 0; + } + + + // 7.2 White Space + + function isWhiteSpace(ch) { + return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') || + (ch === '\u000C') || (ch === '\u00A0') || + (ch.charCodeAt(0) >= 0x1680 && + '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0); + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029'); + } + + // 7.6 Identifier Names and Identifiers + + function isIdentifierStart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch)); + } + + function isIdentifierPart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch >= '0') && (ch <= '9')) || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch)); + } + + // 7.6.1.2 Future Reserved Words + + function isFutureReservedWord(id) { + switch (id) { + + // Future reserved words. + case 'class': + case 'enum': + case 'export': + case 'extends': + case 'import': + case 'super': + return true; + } + + return false; + } + + function isStrictModeReservedWord(id) { + switch (id) { + + // Strict Mode reserved words. + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'yield': + case 'let': + return true; + } + + return false; + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + // 7.6.1.1 Keywords + + function isKeyword(id) { + var keyword = false; + switch (id.length) { + case 2: + keyword = (id === 'if') || (id === 'in') || (id === 'do'); + break; + case 3: + keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); + break; + case 4: + keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with'); + break; + case 5: + keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw'); + break; + case 6: + keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch'); + break; + case 7: + keyword = (id === 'default') || (id === 'finally'); + break; + case 8: + keyword = (id === 'function') || (id === 'continue') || (id === 'debugger'); + break; + case 10: + keyword = (id === 'instanceof'); + break; + } + + if (keyword) { + return true; + } + + switch (id) { + // Future reserved words. + // 'const' is specialized as Keyword in V8. + case 'const': + return true; + + // For compatiblity to SpiderMonkey and ES.next + case 'yield': + case 'let': + return true; + } + + if (strict && isStrictModeReservedWord(id)) { + return true; + } + + return isFutureReservedWord(id); + } + + // Return the next character and move forward. + + function nextChar() { + return source[index++]; + } + + + function isNewlineOrSemicolon(ch) { + return ch===';' || ch==='\n'; + } + + /** + * rewind the lex position to the most recent newline or semicolon. If that turns out + * to be the same position as the most recent parsing of a statement was attempted at, + * don't rewind (because it will fail in the same way). If it turns out to be the same + * position as where we last rewound to, don't do it. Clears the buffer and sets the + * index in order to continue lexing from the new position. + */ + function rewind() { + var idx = index; + while (idx>0 && !isNewlineOrSemicolon(source[idx])) { + idx--; + } + if (idx<=extra.statementStart) { + return; + } + var doRewind = false; + if (extra.lastRewindLocation) { + doRewind = true; + } else { + var v = extra.lastRewindLocation; + if (v!==idx) { + doRewind=true; + } + } + if (doRewind) { + index = idx; + buffer = null; + extra.lastRewindLocation = index; + } + } + + // 7.4 Comments + + function skipComment() { + var ch, blockComment, lineComment; + + blockComment = false; + lineComment = false; + + while (index < length) { + ch = source[index]; + + if (lineComment) { + ch = nextChar(); + if (isLineTerminator(ch)) { + lineComment = false; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + } + } else if (blockComment) { + if (isLineTerminator(ch)) { + if (ch === '\r' && source[index + 1] === '\n') { + ++index; + } + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + ch = nextChar(); + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + if (ch === '*') { + ch = source[index]; + if (ch === '/') { + ++index; + blockComment = false; + } + } + } + } else if (ch === '/') { + ch = source[index + 1]; + if (ch === '/') { + index += 2; + lineComment = true; + } else if (ch === '*') { + index += 2; + blockComment = true; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + break; + } + } else if (isWhiteSpace(ch)) { + ++index; + } else if (isLineTerminator(ch)) { + ++index; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + } else { + break; + } + } + } + + function scanHexEscape(prefix) { + var i, len, ch, code = 0; + + len = (prefix === 'u') ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && isHexDigit(source[index])) { + ch = nextChar(); + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } + + function scanIdentifier() { + var ch, start, id, restore; + + ch = source[index]; + if (!isIdentifierStart(ch)) { + return; + } + + start = index; + if (ch === '\\') { + ++index; + if (source[index] !== 'u') { + return; + } + ++index; + restore = index; + ch = scanHexEscape('u'); + if (ch) { + if (ch === '\\' || !isIdentifierStart(ch)) { + return; + } + id = ch; + } else { + index = restore; + id = 'u'; + } + } else { + id = nextChar(); + } + + while (index < length) { + ch = source[index]; + if (!isIdentifierPart(ch)) { + break; + } + if (ch === '\\') { + ++index; + if (source[index] !== 'u') { + return; + } + ++index; + restore = index; + ch = scanHexEscape('u'); + if (ch) { + if (ch === '\\' || !isIdentifierPart(ch)) { + return; + } + id += ch; + } else { + index = restore; + id += 'u'; + } + } else { + id += nextChar(); + } + } + + // There is no keyword or literal with only one character. + // Thus, it must be an identifier. + if (id.length === 1) { + return { + type: Token.Identifier, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (isKeyword(id)) { + return { + type: Token.Keyword, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 7.8.1 Null Literals + + if (id === 'null') { + return { + type: Token.NullLiteral, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 7.8.2 Boolean Literals + + if (id === 'true' || id === 'false') { + return { + type: Token.BooleanLiteral, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + return { + type: Token.Identifier, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 7.7 Punctuators + + function scanPunctuator() { + var start = index, + ch1 = source[index], + ch2, + ch3, + ch4; + + // Check for most common single-character punctuators. + + if (ch1 === ';' || ch1 === '{' || ch1 === '}') { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === ',' || ch1 === '(' || ch1 === ')') { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // Dot (.) can also start a floating-point number, hence the need + // to check the next character. + + ch2 = source[index + 1]; + if (ch1 === '.' && !isDecimalDigit(ch2)) { + return { + type: Token.Punctuator, + value: nextChar(), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // Peek more characters. + + ch3 = source[index + 2]; + ch4 = source[index + 3]; + + // 4-character punctuator: >>>= + + if (ch1 === '>' && ch2 === '>' && ch3 === '>') { + if (ch4 === '=') { + index += 4; + return { + type: Token.Punctuator, + value: '>>>=', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + // 3-character punctuators: === !== >>> <<= >>= + + if (ch1 === '=' && ch2 === '=' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '===', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '!' && ch2 === '=' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '!==', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '>' && ch2 === '>' && ch3 === '>') { + index += 3; + return { + type: Token.Punctuator, + value: '>>>', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '<' && ch2 === '<' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '<<=', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === '>' && ch2 === '>' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '>>=', + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 2-character punctuators: <= >= == != ++ -- << >> && || + // += -= *= %= &= |= ^= /= + + if (ch2 === '=') { + if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { + index += 2; + return { + type: Token.Punctuator, + value: ch1 + ch2, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) { + if ('+-<>&|'.indexOf(ch2) >= 0) { + index += 2; + return { + type: Token.Punctuator, + value: ch1 + ch2, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + // The remaining 1-character punctuators. + + if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) { + return { + type: Token.Punctuator, + value: nextChar(), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + // 7.8.3 Numeric Literals + + function scanNumericLiteral() { + var number, start, ch; + + ch = source[index]; + assert(isDecimalDigit(ch) || (ch === '.'), + 'Numeric literal must start with a decimal digit or a decimal point'); + + start = index; + number = ''; + if (ch !== '.') { + number = nextChar(); + ch = source[index]; + + // Hex number starts with '0x'. + // Octal number starts with '0'. + if (number === '0') { + if (ch === 'x' || ch === 'X') { + number += nextChar(); + while (index < length) { + ch = source[index]; + if (!isHexDigit(ch)) { + break; + } + number += nextChar(); + } + + if (number.length <= 2) { + // only 0x + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch)) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + return { + type: Token.NumericLiteral, + value: parseInt(number, 16), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } else if (isOctalDigit(ch)) { + number += nextChar(); + while (index < length) { + ch = source[index]; + if (!isOctalDigit(ch)) { + break; + } + number += nextChar(); + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch) || isDecimalDigit(ch)) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + return { + type: Token.NumericLiteral, + value: parseInt(number, 8), + octal: true, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // decimal number starts with '0' such as '09' is illegal. + if (isDecimalDigit(ch)) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += nextChar(); + } + } + + if (ch === '.') { + number += nextChar(); + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += nextChar(); + } + } + + if (ch === 'e' || ch === 'E') { + number += nextChar(); + + ch = source[index]; + if (ch === '+' || ch === '-') { + number += nextChar(); + } + + ch = source[index]; + if (isDecimalDigit(ch)) { + number += nextChar(); + while (index < length) { + ch = source[index]; + if (!isDecimalDigit(ch)) { + break; + } + number += nextChar(); + } + } else { + ch = 'character ' + ch; + if (index >= length) { + ch = ''; + } + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + if (index < length) { + ch = source[index]; + if (isIdentifierStart(ch)) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + return { + type: Token.NumericLiteral, + value: parseFloat(number), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // 7.8.4 String Literals + + function scanStringLiteral() { + var str = '', quote, start, ch, code, unescaped, restore, octal = false; + + quote = source[index]; + assert((quote === '\'' || quote === '"'), + 'String literal must starts with a quote'); + + start = index; + ++index; + + while (index < length) { + ch = nextChar(); + + if (ch === quote) { + quote = ''; + break; + } else if (ch === '\\') { + ch = nextChar(); + if (!isLineTerminator(ch)) { + switch (ch) { + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'u': + case 'x': + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + str += unescaped; + } else { + index = restore; + str += ch; + } + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\v'; + break; + + default: + if (isOctalDigit(ch)) { + code = '01234567'.indexOf(ch); + + // \0 is not octal escape sequence + if (code !== 0) { + octal = true; + } + + if (index < length && isOctalDigit(source[index])) { + octal = true; + code = code * 8 + '01234567'.indexOf(nextChar()); + + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && + index < length && + isOctalDigit(source[index])) { + code = code * 8 + '01234567'.indexOf(nextChar()); + } + } + str += String.fromCharCode(code); + } else { + str += ch; + } + break; + } + } else { + ++lineNumber; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + } + } else if (isLineTerminator(ch)) { + break; + } else { + str += ch; + } + } + + if (quote !== '') { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.StringLiteral, + value: str, + octal: octal, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + function scanRegExp() { + var str = '', ch, start, pattern, flags, value, classMarker = false, restore; + + buffer = null; + skipComment(); + + start = index; + ch = source[index]; + assert(ch === '/', 'Regular expression literal must start with a slash'); + str = nextChar(); + + while (index < length) { + ch = nextChar(); + str += ch; + if (classMarker) { + if (ch === ']') { + classMarker = false; + } + } else { + if (ch === '\\') { + ch = nextChar(); + // ECMA-262 7.8.5 + if (isLineTerminator(ch)) { + throwError({}, Messages.UnterminatedRegExp); + } + str += ch; + } + else if (ch === '/') { + break; + } + else if (ch === '[') { + classMarker = true; + } + else if (isLineTerminator(ch)) { + throwError({}, Messages.UnterminatedRegExp); + } + } + } + + if (str.length === 1) { + throwError({}, Messages.UnterminatedRegExp); + } + + // Exclude leading and trailing slash. + pattern = str.substr(1, str.length - 2); + + flags = ''; + while (index < length) { + ch = source[index]; + if (!isIdentifierPart(ch)) { + break; + } + + ++index; + if (ch === '\\' && index < length) { + ch = source[index]; + if (ch === 'u') { + ++index; + restore = index; + ch = scanHexEscape('u'); + if (ch) { + flags += ch; + str += '\\u'; + for (; restore < index; ++restore) { + str += source[restore]; + } + } else { + index = restore; + flags += 'u'; + str += '\\u'; + } + } else { + str += '\\'; + } + } else { + flags += ch; + str += ch; + } + } + + try { + value = new RegExp(pattern, flags); + } catch (e) { + throwError({}, Messages.InvalidRegExp); + } + + return { + literal: str, + value: value, + range: [start, index] + }; + } + + function isIdentifierName(token) { + return token.type === Token.Identifier || + token.type === Token.Keyword || + token.type === Token.BooleanLiteral || + token.type === Token.NullLiteral; + } + + function advance() { + var ch, token; + + skipComment(); + + if (index >= length) { + return { + type: Token.EOF, + lineNumber: lineNumber, + lineStart: lineStart, + range: [index, index] + }; + } + + token = scanPunctuator(); + if (typeof token !== 'undefined') { + return token; + } + + ch = source[index]; + + if (ch === '\'' || ch === '"') { + return scanStringLiteral(); + } + + if (ch === '.' || isDecimalDigit(ch)) { + return scanNumericLiteral(); + } + + token = scanIdentifier(); + if (typeof token !== 'undefined') { + return token; + } + + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + function lex() { + var token; + + if (buffer) { + index = buffer.range[1]; + lineNumber = buffer.lineNumber; + lineStart = buffer.lineStart; + token = buffer; + buffer = null; + return token; + } + + buffer = null; + return advance(); + } + + function lookahead() { + var pos, line, start; + + if (buffer !== null) { + return buffer; + } + + pos = index; + line = lineNumber; + start = lineStart; + buffer = advance(); + index = pos; + lineNumber = line; + lineStart = start; + + return buffer; + } + + // Return true if there is a line terminator before the next token. + + function peekLineTerminator() { + var pos, line, start, found; + + pos = index; + line = lineNumber; + start = lineStart; + skipComment(); + found = lineNumber !== line; + index = pos; + lineNumber = line; + lineStart = start; + + return found; + } + + // Throw an exception + + function throwError(token, messageFormat) { + var error, + args = Array.prototype.slice.call(arguments, 2), + msg = messageFormat.replace( + /%(\d)/g, + function (whole, index) { + return args[index] || ''; + } + ); + + if (typeof token.lineNumber === 'number') { + error = new Error('Line ' + token.lineNumber + ': ' + msg); + error.index = token.range[0]; + error.lineNumber = token.lineNumber; + error.column = token.range[0] - lineStart + 1; + } else { + error = new Error('Line ' + lineNumber + ': ' + msg); + error.index = index; + error.lineNumber = lineNumber; + error.column = index - lineStart + 1; + } + + throw error; + } + + function throwErrorTolerant() { + var error; + try { + throwError.apply(null, arguments); + } catch (e) { + if (extra.errors) { + extra.errors.push(e); + } else { + throw e; + } + } + } + + + // Throw an exception because of the token. + + function throwUnexpected(token) { + var s; + + if (token.type === Token.EOF) { + throwError(token, Messages.UnexpectedEOS); + } + + if (token.type === Token.NumericLiteral) { + throwError(token, Messages.UnexpectedNumber); + } + + if (token.type === Token.StringLiteral) { + throwError(token, Messages.UnexpectedString); + } + + if (token.type === Token.Identifier) { + throwError(token, Messages.UnexpectedIdentifier); + } + + if (token.type === Token.Keyword) { + if (isFutureReservedWord(token.value)) { + throwError(token, Messages.UnexpectedReserved); + } else if (strict && isStrictModeReservedWord(token.value)) { + throwError(token, Messages.StrictReservedWord); + } + throwError(token, Messages.UnexpectedToken, token.value); + } + + // BooleanLiteral, NullLiteral, or Punctuator. + throwError(token, Messages.UnexpectedToken, token.value); + } + + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + + function expect(value) { + var token = lex(); + if (token.type !== Token.Punctuator || token.value !== value) { + throwUnexpected(token); + } + } + + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + + function expectKeyword(keyword) { + var token = lex(); + if (token.type !== Token.Keyword || token.value !== keyword) { + throwUnexpected(token); + } + } + + // Return true if the next token matches the specified punctuator. + + function match(value) { + var token = lookahead(); + return token.type === Token.Punctuator && token.value === value; + } + + // Return true if the next token matches the specified keyword + + function matchKeyword(keyword) { + var token = lookahead(); + return token.type === Token.Keyword && token.value === keyword; + } + + // Return true if the next token is an assignment operator + + function matchAssign() { + var token = lookahead(), + op = token.value; + + if (token.type !== Token.Punctuator) { + return false; + } + return op === '=' || + op === '*=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + } + + function consumeSemicolon() { + var token, line; + + // Catch the very common case first. + if (source[index] === ';') { + lex(); + return; + } + + line = lineNumber; + skipComment(); + if (lineNumber !== line) { + return; + } + + if (match(';')) { + lex(); + return; + } + + token = lookahead(); + if (token.type !== Token.EOF && !match('}')) { + if (extra.errors) { + rewind(); + } + throwUnexpected(token); + } + return; + } + + // Return true if provided expression is LeftHandSideExpression + + function isLeftHandSide(expr) { + switch (expr.type) { + case 'AssignmentExpression': + case 'BinaryExpression': + case 'ConditionalExpression': + case 'LogicalExpression': + case 'SequenceExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return false; + } + return true; + } + + // 11.1.4 Array Initialiser + + function parseArrayInitialiser() { + var elements = [], + undef; + + expect('['); + + while (!match(']')) { + if (match(',')) { + lex(); + elements.push(undef); + } else { + elements.push(parseAssignmentExpression()); + + if (!match(']')) { + expect(','); + } + } + } + + expect(']'); + + return { + type: Syntax.ArrayExpression, + elements: elements + }; + } + + // 11.1.5 Object Initialiser + + function parsePropertyFunction(param, first) { + var previousStrict, body; + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (first && strict && isRestrictedWord(param[0].name)) { + throwError(first, Messages.StrictParamName); + } + strict = previousStrict; + + return { + type: Syntax.FunctionExpression, + id: null, + params: param, + body: body + }; + } + + function parseObjectPropertyKey() { + var token = lex(); + + // Note: This function is called only from parseObjectProperty(), where + // EOF and Punctuator tokens are already filtered out. + + if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { + if (strict && token.octal) { + throwError(token, Messages.StrictOctalLiteral); + } + return createLiteral(token); + } + + return { + type: Syntax.Identifier, + name: token.value + }; + } + + function parseObjectProperty() { + var token, key, id, param; + + token = lookahead(); + + if (token.type === Token.Identifier) { + + id = parseObjectPropertyKey(); + + // Property Assignment: Getter and Setter. + + if (token.value === 'get' && !match(':')) { + key = parseObjectPropertyKey(); + expect('('); + expect(')'); + return { + type: Syntax.Property, + key: key, + value: parsePropertyFunction([]), + kind: 'get' + }; + } else if (token.value === 'set' && !match(':')) { + key = parseObjectPropertyKey(); + expect('('); + token = lookahead(); + if (token.type !== Token.Identifier) { + throwUnexpected(lex()); + } + param = [ parseVariableIdentifier() ]; + expect(')'); + return { + type: Syntax.Property, + key: key, + value: parsePropertyFunction(param, token), + kind: 'set' + }; + } else { + expect(':'); + return { + type: Syntax.Property, + key: id, + value: parseAssignmentExpression(), + kind: 'init' + }; + } + } else if (token.type === Token.EOF || token.type === Token.Punctuator) { + throwUnexpected(token); + } else { + key = parseObjectPropertyKey(); + expect(':'); + return { + type: Syntax.Property, + key: key, + value: parseAssignmentExpression(), + kind: 'init' + }; + } + } + + function parseObjectInitialiser() { + var token, properties = [], property, name, kind, map = {}, toString = String; + + expect('{'); + + while (!match('}')) { + property = parseObjectProperty(); + + if (property.key.type === Syntax.Identifier) { + name = property.key.name; + } else { + name = toString(property.key.value); + } + kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; + if (Object.prototype.hasOwnProperty.call(map, name)) { + if (map[name] === PropertyKind.Data) { + if (strict && kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.StrictDuplicateProperty); + } else if (kind !== PropertyKind.Data) { + throwError({}, Messages.AccessorDataProperty); + } + } else { + if (kind === PropertyKind.Data) { + throwError({}, Messages.AccessorDataProperty); + } else if (map[name] & kind) { + throwError({}, Messages.AccessorGetSet); + } + } + map[name] |= kind; + } else { + map[name] = kind; + } + + properties.push(property); + + if (!match('}')) { + expect(','); + } + } + + expect('}'); + + return { + type: Syntax.ObjectExpression, + properties: properties + }; + } + + // 11.1 Primary Expressions + + function parsePrimaryExpression() { + var expr, + token = lookahead(), + type = token.type; + + if (type === Token.Identifier) { + return { + type: Syntax.Identifier, + name: lex().value + }; + } + + if (type === Token.StringLiteral || type === Token.NumericLiteral) { + if (strict && token.octal) { + throwErrorTolerant(token, Messages.StrictOctalLiteral); + } + return createLiteral(lex()); + } + + if (type === Token.Keyword) { + if (matchKeyword('this')) { + lex(); + return { + type: Syntax.ThisExpression + }; + } + + if (matchKeyword('function')) { + return parseFunctionExpression(); + } + } + + if (type === Token.BooleanLiteral) { + lex(); + token.value = (token.value === 'true'); + return createLiteral(token); + } + + if (type === Token.NullLiteral) { + lex(); + token.value = null; + return createLiteral(token); + } + + if (match('[')) { + return parseArrayInitialiser(); + } + + if (match('{')) { + return parseObjectInitialiser(); + } + + if (match('(')) { + lex(); + state.lastParenthesized = expr = parseExpression(); + expect(')'); + return expr; + } + + if (match('/') || match('/=')) { + return createLiteral(scanRegExp()); + } + + return throwUnexpected(lex()); + } + + // 11.2 Left-Hand-Side Expressions + + function parseArguments() { + var args = []; + + expect('('); + + if (!match(')')) { + while (index < length) { + args.push(parseAssignmentExpression()); + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + return args; + } + + // TODO refactor + /** + * From a position 'idx' in the source this function moves back through the source until + * it finds a non-whitespace (including newlines) character. It will jump over block comments. + * Returns an object with properties: index - the index it rewound to. lineChange - boolean indicating + * if a line was crossed during rewind. + */ + function rewindToInterestingChar(idx) { + var done = false; + var lineChange=false; + var ch; + while (!done) { + ch = source[idx]; + if (ch==='/') { + // possibly rewind over a block comment + if (idx>2 && source[idx-1]==='*') { + // it is, let's reverse over it + idx = idx - 2; + var skippedComment = false; + while (!skippedComment) { + ch = source[idx]; + if (ch === '*') { + if (idx>0 && source[idx-1]==='/') { + skippedComment=true; + } + } else if (ch==='\n') { + lineChange=true; + } + if (idx === 0) { + skippedComment = true; // error scenario, hit front of array before finding /* + } + idx--; + } + } else { + done=true; + } + } else + if (ch==='\n') { + lineChange=true; + } else if (!isWhiteSpace(ch)) { + done=true; + } + if (!done) { + idx--; + } + } + return {"index":idx,"lineChange":lineChange}; + } + + /** + * When a problem occurs in parseNonComputedProperty, attempt to reposition + * the lexer to continue processing. + * Example: '(foo.)' we will hit the ')' instead of discovering a property and consuming the ')' + * will cause the parse of the paretheses to fail, so 'unconsume' it. + * Basically rewind by one token if punctuation (type 7) is hit and the char before it was + * a dot. This will enable the enclosing parse rule to consume the punctuation. + */ + function attemptRecoveryNonComputedProperty(token) { + if (token.value && token.type===Token.Punctuator) { + var rewindInfo = rewindToInterestingChar(index-token.value.length-1); + var idx = rewindInfo.index; + var ch= source[idx]; + // Check if worth rewinding + // Special case: + // "foo.\n(foo())\n" - don't really want that to parse as "foo(foo())" + if (ch==='.' && rewindInfo.lineChange && token.value==='(') { + // do not recover in this case + } else if (ch==='.') { + index = idx+1; + buffer=null; + } + } + } + + + function parseNonComputedProperty() { + var token = lex(); + + if (!isIdentifierName(token)) { + if (extra.errors) { + attemptRecoveryNonComputedProperty(token); + } + throwUnexpected(token); + } + + return { + type: Syntax.Identifier, + name: token.value + }; + } + + function parseNonComputedMember(object) { + return { + type: Syntax.MemberExpression, + computed: false, + object: object, + property: parseNonComputedProperty() + }; + } + + function parseComputedMember(object) { + var property, expr; + + expect('['); + property = parseExpression(); + expr = { + type: Syntax.MemberExpression, + computed: true, + object: object, + property: property + }; + expect(']'); + return expr; + } + + function parseCallMember(object) { + return { + type: Syntax.CallExpression, + callee: object, + 'arguments': parseArguments() + }; + } + + function parseNewExpression() { + var expr; + + expectKeyword('new'); + + expr = { + type: Syntax.NewExpression, + callee: parseLeftHandSideExpression(), + 'arguments': [] + }; + + if (match('(')) { + expr['arguments'] = parseArguments(); + } + + return expr; + } + + function parseLeftHandSideExpressionAllowCall() { + var useNew, expr; + + useNew = matchKeyword('new'); + expr = useNew ? parseNewExpression() : parsePrimaryExpression(); + + while (index < length) { + if (match('.')) { + lex(); + expr = parseNonComputedMember(expr); + } else if (match('[')) { + expr = parseComputedMember(expr); + } else if (match('(')) { + expr = parseCallMember(expr); + } else { + break; + } + } + + return expr; + } + + function parseLeftHandSideExpression() { + var useNew, expr; + + useNew = matchKeyword('new'); + expr = useNew ? parseNewExpression() : parsePrimaryExpression(); + + while (index < length) { + if (match('.')) { + lex(); + expr = parseNonComputedMember(expr); + } else if (match('[')) { + expr = parseComputedMember(expr); + } else { + break; + } + } + + return expr; + } + + // 11.3 Postfix Expressions + + function parsePostfixExpression() { + var expr = parseLeftHandSideExpressionAllowCall(); + + if ((match('++') || match('--')) && !peekLineTerminator()) { + // 11.3.1, 11.3.2 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwError({}, Messages.StrictLHSPostfix); + } + expr = { + type: Syntax.UpdateExpression, + operator: lex().value, + argument: expr, + prefix: false + }; + } + + return expr; + } + + // 11.4 Unary Operators + + function parseUnaryExpression() { + var token, expr; + + if (match('++') || match('--')) { + token = lex(); + expr = parseUnaryExpression(); + // 11.4.4, 11.4.5 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwError({}, Messages.StrictLHSPrefix); + } + expr = { + type: Syntax.UpdateExpression, + operator: token.value, + argument: expr, + prefix: true + }; + return expr; + } + + if (match('+') || match('-') || match('~') || match('!')) { + expr = { + type: Syntax.UnaryExpression, + operator: lex().value, + argument: parseUnaryExpression() + }; + return expr; + } + + if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { + expr = { + type: Syntax.UnaryExpression, + operator: lex().value, + argument: parseUnaryExpression() + }; + if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { + throwErrorTolerant({}, Messages.StrictDelete); + } + return expr; + } + + return parsePostfixExpression(); + } + + // 11.5 Multiplicative Operators + + function parseMultiplicativeExpression() { + var expr = parseUnaryExpression(); + + while (match('*') || match('/') || match('%')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseUnaryExpression() + }; + } + + return expr; + } + + // 11.6 Additive Operators + + function parseAdditiveExpression() { + var expr = parseMultiplicativeExpression(); + + while (match('+') || match('-')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseMultiplicativeExpression() + }; + } + + return expr; + } + + // 11.7 Bitwise Shift Operators + + function parseShiftExpression() { + var expr = parseAdditiveExpression(); + + while (match('<<') || match('>>') || match('>>>')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseAdditiveExpression() + }; + } + + return expr; + } + // 11.8 Relational Operators + + function parseRelationalExpression() { + var expr, previousAllowIn; + + previousAllowIn = state.allowIn; + state.allowIn = true; + expr = parseShiftExpression(); + state.allowIn = previousAllowIn; + + if (match('<') || match('>') || match('<=') || match('>=')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseRelationalExpression() + }; + } else if (state.allowIn && matchKeyword('in')) { + lex(); + expr = { + type: Syntax.BinaryExpression, + operator: 'in', + left: expr, + right: parseRelationalExpression() + }; + } else if (matchKeyword('instanceof')) { + lex(); + expr = { + type: Syntax.BinaryExpression, + operator: 'instanceof', + left: expr, + right: parseRelationalExpression() + }; + } + + return expr; + } + + // 11.9 Equality Operators + + function parseEqualityExpression() { + var expr = parseRelationalExpression(); + + while (match('==') || match('!=') || match('===') || match('!==')) { + expr = { + type: Syntax.BinaryExpression, + operator: lex().value, + left: expr, + right: parseRelationalExpression() + }; + } + + return expr; + } + + // 11.10 Binary Bitwise Operators + + function parseBitwiseANDExpression() { + var expr = parseEqualityExpression(); + + while (match('&')) { + lex(); + expr = { + type: Syntax.BinaryExpression, + operator: '&', + left: expr, + right: parseEqualityExpression() + }; + } + + return expr; + } + + function parseBitwiseORExpression() { + var expr = parseBitwiseANDExpression(); + + while (match('|')) { + lex(); + expr = { + type: Syntax.BinaryExpression, + operator: '|', + left: expr, + right: parseBitwiseANDExpression() + }; + } + + return expr; + } + + function parseBitwiseXORExpression() { + var expr = parseBitwiseORExpression(); + + while (match('^')) { + lex(); + expr = { + type: Syntax.BinaryExpression, + operator: '^', + left: expr, + right: parseBitwiseORExpression() + }; + } + + return expr; + } + + // 11.11 Binary Logical Operators + + function parseLogicalANDExpression() { + var expr = parseBitwiseXORExpression(); + + while (match('&&')) { + lex(); + expr = { + type: Syntax.LogicalExpression, + operator: '&&', + left: expr, + right: parseBitwiseXORExpression() + }; + } + + return expr; + } + + function parseLogicalORExpression() { + var expr = parseLogicalANDExpression(); + + while (match('||')) { + lex(); + expr = { + type: Syntax.LogicalExpression, + operator: '||', + left: expr, + right: parseLogicalANDExpression() + }; + } + + return expr; + } + + // 11.12 Conditional Operator + + function parseConditionalExpression() { + var expr, previousAllowIn, consequent; + + expr = parseLogicalORExpression(); + + if (match('?')) { + lex(); + previousAllowIn = state.allowIn; + state.allowIn = true; + consequent = parseAssignmentExpression(); + state.allowIn = previousAllowIn; + expect(':'); + + expr = { + type: Syntax.ConditionalExpression, + test: expr, + consequent: consequent, + alternate: parseAssignmentExpression() + }; + } + + return expr; + } + + // 11.13 Assignment Operators + + function parseAssignmentExpression() { + var expr; + + expr = parseConditionalExpression(); + + if (matchAssign()) { + // LeftHandSideExpression + if (state.lastParenthesized !== expr && !isLeftHandSide(expr)) { + throwError({}, Messages.InvalidLHSInAssignment); + } + + // 11.13.1 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwError({}, Messages.StrictLHSAssignment); + } + + expr = { + type: Syntax.AssignmentExpression, + operator: lex().value, + left: expr, + right: parseAssignmentExpression() + }; + } + + return expr; + } + + // 11.14 Comma Operator + + function parseExpression() { + var expr = parseAssignmentExpression(); + + if (match(',')) { + expr = { + type: Syntax.SequenceExpression, + expressions: [ expr ] + }; + + while (index < length) { + if (!match(',')) { + break; + } + lex(); + expr.expressions.push(parseAssignmentExpression()); + } + + } + return expr; + } + + // 12.1 Block + + function parseStatementList() { + var list = [], + statement; + + while (index < length) { + if (match('}')) { + break; + } + statement = parseSourceElement(); + if (typeof statement === 'undefined') { + break; + } + list.push(statement); + } + + return list; + } + + function parseBlock() { + var block; + + expect('{'); + + block = parseStatementList(); + + expect('}'); + + return { + type: Syntax.BlockStatement, + body: block + }; + } + + // 12.2 Variable Statement + + function parseVariableIdentifier() { + var token = lex(); + + if (token.type !== Token.Identifier) { + throwUnexpected(token); + } + + return { + type: Syntax.Identifier, + name: token.value + }; + } + + function parseVariableDeclaration(kind) { + var id = parseVariableIdentifier(), + init = null; + + // 12.2.1 + if (strict && isRestrictedWord(id.name)) { + throwErrorTolerant({}, Messages.StrictVarName); + } + + if (kind === 'const') { + expect('='); + init = parseAssignmentExpression(); + } else if (match('=')) { + lex(); + init = parseAssignmentExpression(); + } + + return { + type: Syntax.VariableDeclarator, + id: id, + init: init + }; + } + + function parseVariableDeclarationList(kind) { + var list = []; + + while (index < length) { + list.push(parseVariableDeclaration(kind)); + if (!match(',')) { + break; + } + lex(); + } + + return list; + } + + function parseVariableStatement() { + var declarations; + + expectKeyword('var'); + + declarations = parseVariableDeclarationList(); + + consumeSemicolon(); + + return { + type: Syntax.VariableDeclaration, + declarations: declarations, + kind: 'var' + }; + } + + // kind may be `const` or `let` + // Both are experimental and not in the specification yet. + // see http://wiki.ecmascript.org/doku.php?id=harmony:const + // and http://wiki.ecmascript.org/doku.php?id=harmony:let + function parseConstLetDeclaration(kind) { + var declarations; + + expectKeyword(kind); + + declarations = parseVariableDeclarationList(kind); + + consumeSemicolon(); + + return { + type: Syntax.VariableDeclaration, + declarations: declarations, + kind: kind + }; + } + + // 12.3 Empty Statement + + function parseEmptyStatement() { + expect(';'); + + return { + type: Syntax.EmptyStatement + }; + } + + // 12.4 Expression Statement + + function parseExpressionStatement() { + var expr = parseExpression(); + + consumeSemicolon(); + + return { + type: Syntax.ExpressionStatement, + expression: expr + }; + } + + /** + * add the error if not already reported. + */ + function pushError(error) { + var len = extra.errors.length; + for (var e=0; e < len; e++) { + var existingError = extra.errors[e]; + if (existingError.index === error.index && existingError.message === error.message) { + return; // do not add duplicate + } + } + extra.errors.push(error); + } + + // 12.5 If statement + + function parseIfStatement() { + var test, consequent, alternate; + + expectKeyword('if'); + + expect('('); + + test = parseExpression(); + + // needs generalizing to a 'expect A but don't consume if you hit B or C' + try { + expect(')'); + } catch (e) { + if (extra.errors) { + pushError(e); + // If a { was hit instead of a ) then don't consume it, let us assume a ')' was + // missed and the consequent block is OK + if (source[e.index] === '{') { + index=e.index; + buffer=null; + // activating this block will mean the following statement is parsed as a consequent. + // without it the statement is considered not at all part of the if at all + // } else { + // rewind(); + } + } else { + throw e; + } + } + + consequent = parseStatement(); + // required because of the check in wrapTracking that returns nothing if node is undefined + if (!consequent) { + consequent = null; + } + + if (matchKeyword('else')) { + lex(); + alternate = parseStatement(); + } else { + alternate = null; + } + + return { + type: Syntax.IfStatement, + test: test, + consequent: consequent, + alternate: alternate + }; + } + + // 12.6 Iteration Statements + + function parseDoWhileStatement() { + var body, test, oldInIteration; + + expectKeyword('do'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + if (match(';')) { + lex(); + } + + return { + type: Syntax.DoWhileStatement, + body: body, + test: test + }; + } + + function parseWhileStatement() { + var test, body, oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + return { + type: Syntax.WhileStatement, + test: test, + body: body + }; + } + + function parseForVariableDeclaration() { + var token = lex(); + + return { + type: Syntax.VariableDeclaration, + declarations: parseVariableDeclarationList(), + kind: token.value + }; + } + + function parseForStatement() { + var init, test, update, left, right, body, oldInIteration; + + init = test = update = null; + + expectKeyword('for'); + + expect('('); + + if (match(';')) { + lex(); + } else { + if (matchKeyword('var') || matchKeyword('let')) { + state.allowIn = false; + init = parseForVariableDeclaration(); + state.allowIn = true; + + if (init.declarations.length === 1 && matchKeyword('in')) { + lex(); + left = init; + right = parseExpression(); + init = null; + } + } else { + state.allowIn = false; + init = parseExpression(); + state.allowIn = true; + + if (matchKeyword('in')) { + // LeftHandSideExpression + if (matchKeyword('in') && (state.lastParenthesized !== init && !isLeftHandSide(init))) { + throwError({}, Messages.InvalidLHSInForIn); + } + lex(); + left = init; + right = parseExpression(); + init = null; + } + } + + if (typeof left === 'undefined') { + expect(';'); + } + } + + if (typeof left === 'undefined') { + + if (!match(';')) { + test = parseExpression(); + } + expect(';'); + + if (!match(')')) { + update = parseExpression(); + } + } + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + if (typeof left === 'undefined') { + return { + type: Syntax.ForStatement, + init: init, + test: test, + update: update, + body: body + }; + } + + return { + type: Syntax.ForInStatement, + left: left, + right: right, + body: body, + each: false + }; + } + + // 12.7 The continue statement + + function parseContinueStatement() { + var token, label = null; + + expectKeyword('continue'); + + // Optimize the most common form: 'continue;'. + if (source[index] === ';') { + lex(); + + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return { + type: Syntax.ContinueStatement, + label: null + }; + } + + if (peekLineTerminator()) { + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return { + type: Syntax.ContinueStatement, + label: null + }; + } + + token = lookahead(); + if (token.type === Token.Identifier) { + label = parseVariableIdentifier(); + + if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return { + type: Syntax.ContinueStatement, + label: label + }; + } + + // 12.8 The break statement + + function parseBreakStatement() { + var token, label = null; + + expectKeyword('break'); + + // Optimize the most common form: 'break;'. + if (source[index] === ';') { + lex(); + + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return { + type: Syntax.BreakStatement, + label: null + }; + } + + if (peekLineTerminator()) { + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return { + type: Syntax.BreakStatement, + label: null + }; + } + + token = lookahead(); + if (token.type === Token.Identifier) { + label = parseVariableIdentifier(); + + if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return { + type: Syntax.BreakStatement, + label: label + }; + } + + // 12.9 The return statement + + function parseReturnStatement() { + var token, argument = null; + + expectKeyword('return'); + + if (!state.inFunctionBody) { + throwErrorTolerant({}, Messages.IllegalReturn); + } + + // 'return' followed by a space and an identifier is very common. + if (source[index] === ' ') { + if (isIdentifierStart(source[index + 1])) { + argument = parseExpression(); + consumeSemicolon(); + return { + type: Syntax.ReturnStatement, + argument: argument + }; + } + } + + if (peekLineTerminator()) { + return { + type: Syntax.ReturnStatement, + argument: null + }; + } + + if (!match(';')) { + token = lookahead(); + if (!match('}') && token.type !== Token.EOF) { + argument = parseExpression(); + } + } + + consumeSemicolon(); + + return { + type: Syntax.ReturnStatement, + argument: argument + }; + } + + // 12.10 The with statement + + function parseWithStatement() { + var object, body; + + if (strict) { + throwErrorTolerant({}, Messages.StrictModeWith); + } + + expectKeyword('with'); + + expect('('); + + object = parseExpression(); + + expect(')'); + + body = parseStatement(); + + return { + type: Syntax.WithStatement, + object: object, + body: body + }; + } + + // 12.10 The swith statement + + function parseSwitchCase() { + var test, + consequent = [], + statement; + + if (matchKeyword('default')) { + lex(); + test = null; + } else { + expectKeyword('case'); + test = parseExpression(); + } + expect(':'); + + while (index < length) { + if (match('}') || matchKeyword('default') || matchKeyword('case')) { + break; + } + statement = parseStatement(); + if (typeof statement === 'undefined') { + break; + } + consequent.push(statement); + } + + return { + type: Syntax.SwitchCase, + test: test, + consequent: consequent + }; + } + + function parseSwitchStatement() { + var discriminant, cases, oldInSwitch; + + expectKeyword('switch'); + + expect('('); + + discriminant = parseExpression(); + + expect(')'); + + expect('{'); + + if (match('}')) { + lex(); + return { + type: Syntax.SwitchStatement, + discriminant: discriminant + }; + } + + cases = []; + + oldInSwitch = state.inSwitch; + state.inSwitch = true; + + while (index < length) { + if (match('}')) { + break; + } + cases.push(parseSwitchCase()); + } + + state.inSwitch = oldInSwitch; + + expect('}'); + + return { + type: Syntax.SwitchStatement, + discriminant: discriminant, + cases: cases + }; + } + + // 12.13 The throw statement + + function parseThrowStatement() { + var argument; + + expectKeyword('throw'); + + if (peekLineTerminator()) { + throwError({}, Messages.NewlineAfterThrow); + } + + argument = parseExpression(); + + consumeSemicolon(); + + return { + type: Syntax.ThrowStatement, + argument: argument + }; + } + + // 12.14 The try statement + + function parseCatchClause() { + var param; + + expectKeyword('catch'); + + expect('('); + if (!match(')')) { + param = parseExpression(); + // 12.14.1 + if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { + throwErrorTolerant({}, Messages.StrictCatchVariable); + } + } + expect(')'); + + return { + type: Syntax.CatchClause, + param: param, + guard: null, + body: parseBlock() + }; + } + + function parseTryStatement() { + var block, handlers = [], finalizer = null; + + expectKeyword('try'); + + block = parseBlock(); + + if (matchKeyword('catch')) { + handlers.push(parseCatchClause()); + } + + if (matchKeyword('finally')) { + lex(); + finalizer = parseBlock(); + } + + if (handlers.length === 0 && !finalizer) { + throwError({}, Messages.NoCatchOrFinally); + } + + return { + type: Syntax.TryStatement, + block: block, + handlers: handlers, + finalizer: finalizer + }; + } + + // 12.15 The debugger statement + + function parseDebuggerStatement() { + expectKeyword('debugger'); + + consumeSemicolon(); + + return { + type: Syntax.DebuggerStatement + }; + } + + // 12 Statements + + function parseStatement() { + var token = lookahead(), + expr, + labeledBody; + + if (token.type === Token.EOF) { + throwUnexpected(token); + } + + if (token.type === Token.Punctuator) { + switch (token.value) { + case ';': + return parseEmptyStatement(); + case '{': + return parseBlock(); + case '(': + return parseExpressionStatement(); + default: + break; + } + } + + if (token.type === Token.Keyword) { + switch (token.value) { + case 'break': + return parseBreakStatement(); + case 'continue': + return parseContinueStatement(); + case 'debugger': + return parseDebuggerStatement(); + case 'do': + return parseDoWhileStatement(); + case 'for': + return parseForStatement(); + case 'function': + return parseFunctionDeclaration(); + case 'if': + return parseIfStatement(); + case 'return': + return parseReturnStatement(); + case 'switch': + return parseSwitchStatement(); + case 'throw': + return parseThrowStatement(); + case 'try': + return parseTryStatement(); + case 'var': + return parseVariableStatement(); + case 'while': + return parseWhileStatement(); + case 'with': + return parseWithStatement(); + default: + break; + } + } + + expr = parseExpression(); + + // 12.12 Labelled Statements + if (expr && (expr.type === Syntax.Identifier) && match(':')) { + lex(); + + if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) { + throwError({}, Messages.Redeclaration, 'Label', expr.name); + } + + state.labelSet[expr.name] = true; + labeledBody = parseStatement(); + delete state.labelSet[expr.name]; + + return { + type: Syntax.LabeledStatement, + label: expr, + body: labeledBody + }; + } + + consumeSemicolon(); + + + return { + type: Syntax.ExpressionStatement, + expression: expr + }; + } + + // 13 Function Definition + + function parseFunctionSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted, + oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody; + + expect('{'); + + while (index < length) { + token = lookahead(); + if (token.type !== Token.StringLiteral) { + break; + } + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = sliceSource(token.range[0] + 1, token.range[1] - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + throwError(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + oldLabelSet = state.labelSet; + oldInIteration = state.inIteration; + oldInSwitch = state.inSwitch; + oldInFunctionBody = state.inFunctionBody; + + state.labelSet = {}; + state.inIteration = false; + state.inSwitch = false; + state.inFunctionBody = true; + + while (index < length) { + if (match('}')) { + break; + } + sourceElement = parseSourceElement(); + if (typeof sourceElement === 'undefined') { + break; + } + sourceElements.push(sourceElement); + } + + expect('}'); + + state.labelSet = oldLabelSet; + state.inIteration = oldInIteration; + state.inSwitch = oldInSwitch; + state.inFunctionBody = oldInFunctionBody; + + return { + type: Syntax.BlockStatement, + body: sourceElements + }; + } + + function parseFunctionDeclaration() { + var id, param, params = [], body, token, firstRestricted, message, previousStrict, paramSet; + + expectKeyword('function'); + token = lookahead(); + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwError(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + + expect('('); + + if (!match(')')) { + paramSet = {}; + while (index < length) { + token = lookahead(); + param = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwError(token, Messages.StrictParamName); + } + if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { + throwError(token, Messages.StrictParamDupe); + } + } else if (!firstRestricted) { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictParamName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { + firstRestricted = token; + message = Messages.StrictParamDupe; + } + } + params.push(param); + paramSet[param.name] = true; + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + strict = previousStrict; + + return { + type: Syntax.FunctionDeclaration, + id: id, + params: params, + body: body + }; + } + + function parseFunctionExpression() { + var token, id = null, firstRestricted, message, param, params = [], body, previousStrict, paramSet; + + expectKeyword('function'); + + if (!match('(')) { + token = lookahead(); + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwError(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + } + + expect('('); + + if (!match(')')) { + paramSet = {}; + while (index < length) { + token = lookahead(); + param = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwError(token, Messages.StrictParamName); + } + if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { + throwError(token, Messages.StrictParamDupe); + } + } else if (!firstRestricted) { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictParamName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { + firstRestricted = token; + message = Messages.StrictParamDupe; + } + } + params.push(param); + paramSet[param.name] = true; + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + strict = previousStrict; + + return { + type: Syntax.FunctionExpression, + id: id, + params: params, + body: body + }; + } + + // 14 Program + + function parseSourceElement() { + var token = lookahead(); + + if (token.type === Token.Keyword) { + switch (token.value) { + case 'const': + case 'let': + return parseConstLetDeclaration(token.value); + case 'function': + return parseFunctionDeclaration(); + default: + return parseStatement(); + } + } + + if (token.type !== Token.EOF) { + return parseStatement(); + } + } + + function parseSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted; + + while (index < length) { + token = lookahead(); + if (token.type !== Token.StringLiteral) { + break; + } + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = sliceSource(token.range[0] + 1, token.range[1] - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + throwError(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + while (index < length) { + sourceElement = parseSourceElement(); + if (typeof sourceElement === 'undefined') { + break; + } + sourceElements.push(sourceElement); + } + return sourceElements; + } + + function parseProgram() { + var program; + strict = false; + program = { + type: Syntax.Program, + body: parseSourceElements() + }; + return program; + } + + // The following functions are needed only when the option to preserve + // the comments is active. + + function addComment(start, end, type, value) { + assert(typeof start === 'number', 'Comment must have valid position'); + + // Because the way the actual token is scanned, often the comments + // (if any) are skipped twice during the lexical analysis. + // Thus, we need to skip adding a comment if the comment array already + // handled it. + if (extra.comments.length > 0) { + if (extra.comments[extra.comments.length - 1].range[1] > start) { + return; + } + } + + extra.comments.push({ + range: [start, end], + type: type, + value: value + }); + } + + function scanComment() { + var comment, ch, start, blockComment, lineComment; + + comment = ''; + blockComment = false; + lineComment = false; + + while (index < length) { + ch = source[index]; + + if (lineComment) { + ch = nextChar(); + if (index >= length) { + lineComment = false; + comment += ch; + addComment(start, index, 'Line', comment); + } else if (isLineTerminator(ch)) { + lineComment = false; + addComment(start, index, 'Line', comment); + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + comment = ''; + } else { + comment += ch; + } + } else if (blockComment) { + if (isLineTerminator(ch)) { + if (ch === '\r' && source[index + 1] === '\n') { + ++index; + comment += '\r\n'; + } else { + comment += ch; + } + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + ch = nextChar(); + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + comment += ch; + if (ch === '*') { + ch = source[index]; + if (ch === '/') { + comment = comment.substr(0, comment.length - 1); + blockComment = false; + ++index; + addComment(start, index, 'Block', comment); + comment = ''; + } + } + } + } else if (ch === '/') { + ch = source[index + 1]; + if (ch === '/') { + start = index; + index += 2; + lineComment = true; + } else if (ch === '*') { + start = index; + index += 2; + blockComment = true; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else { + break; + } + } else if (isWhiteSpace(ch)) { + ++index; + } else if (isLineTerminator(ch)) { + ++index; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + ++lineNumber; + lineStart = index; + } else { + break; + } + } + } + + function collectToken() { + var token = extra.advance(), + range, + value; + + if (token.type !== Token.EOF) { + range = [token.range[0], token.range[1]]; + value = sliceSource(token.range[0], token.range[1]); + extra.tokens.push({ + type: TokenName[token.type], + value: value, + range: range + }); + } + + return token; + } + + function collectRegex() { + var pos, regex, token; + + skipComment(); + + pos = index; + regex = extra.scanRegExp(); + + // Pop the previous token, which is likely '/' or '/=' + if (extra.tokens.length > 0) { + token = extra.tokens[extra.tokens.length - 1]; + if (token.range[0] === pos && token.type === 'Punctuator') { + if (token.value === '/' || token.value === '/=') { + extra.tokens.pop(); + } + } + } + + extra.tokens.push({ + type: 'RegularExpression', + value: regex.literal, + range: [pos, index] + }); + + return regex; + } + + function createLiteral(token) { + return { + type: Syntax.Literal, + value: token.value + }; + } + + function createRawLiteral(token) { + return { + type: Syntax.Literal, + value: token.value, + raw: sliceSource(token.range[0], token.range[1]) + }; + } + + function wrapTrackingFunction(range, loc) { + + return function (parseFunction) { + + function isBinary(node) { + return node.type === Syntax.LogicalExpression || + node.type === Syntax.BinaryExpression; + } + + function visit(node) { + if (isBinary(node.left)) { + visit(node.left); + } + if (isBinary(node.right)) { + visit(node.right); + } + + if (range && typeof node.range === 'undefined') { + node.range = [node.left.range[0], node.right.range[1]]; + } + if (loc && typeof node.loc === 'undefined') { + node.loc = { + start: node.left.loc.start, + end: node.right.loc.end + }; + } + } + + return function () { + var node, rangeInfo, locInfo; + + skipComment(); + rangeInfo = [index, 0]; + locInfo = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + node = parseFunction.apply(null, arguments); + if (typeof node !== 'undefined') { + + if (range) { + rangeInfo[1] = index; + node.range = rangeInfo; + } + + if (loc) { + locInfo.end = { + line: lineNumber, + column: index - lineStart + }; + node.loc = locInfo; + } + + if (isBinary(node)) { + visit(node); + } + + if (node.type === Syntax.MemberExpression) { + if (typeof node.object.range !== 'undefined') { + node.range[0] = node.object.range[0]; + } + if (typeof node.object.loc !== 'undefined') { + node.loc.start = node.object.loc.start; + } + } + return node; + } + }; + + }; + } + + function patch() { + + var wrapTracking; + + function wrapThrow(parseFunction) { + return function () { + try { + return parseFunction.apply(null, arguments); + } catch (e) { + pushError(e); + return null; + } + }; + } + + function wrapThrowParseStatement(parseFunction) { + return function () { + extra.statementStart = index; // record where attempting to parse statement from + try { + return parseFunction.apply(null, arguments); + } catch (e) { + pushError(e); +// return null; + } + }; + } + + if (extra.comments) { + extra.skipComment = skipComment; + skipComment = scanComment; + } + + if (extra.raw) { + extra.createLiteral = createLiteral; + createLiteral = createRawLiteral; + } + + if (extra.range || extra.loc || extra.errors) { + + wrapTracking = wrapTrackingFunction(extra.range, extra.loc); + + extra.parseAdditiveExpression = parseAdditiveExpression; + extra.parseAssignmentExpression = parseAssignmentExpression; + extra.parseBitwiseANDExpression = parseBitwiseANDExpression; + extra.parseBitwiseORExpression = parseBitwiseORExpression; + extra.parseBitwiseXORExpression = parseBitwiseXORExpression; + extra.parseBlock = parseBlock; + extra.parseFunctionSourceElements = parseFunctionSourceElements; + extra.parseCallMember = parseCallMember; + extra.parseCatchClause = parseCatchClause; + extra.parseComputedMember = parseComputedMember; + extra.parseConditionalExpression = parseConditionalExpression; + extra.parseConstLetDeclaration = parseConstLetDeclaration; + extra.parseEqualityExpression = parseEqualityExpression; + extra.parseExpression = parseExpression; + extra.parseForVariableDeclaration = parseForVariableDeclaration; + extra.parseFunctionDeclaration = parseFunctionDeclaration; + extra.parseFunctionExpression = parseFunctionExpression; + extra.parseLogicalANDExpression = parseLogicalANDExpression; + extra.parseLogicalORExpression = parseLogicalORExpression; + extra.parseMultiplicativeExpression = parseMultiplicativeExpression; + extra.parseNewExpression = parseNewExpression; + extra.parseNonComputedMember = parseNonComputedMember; + extra.parseNonComputedProperty = parseNonComputedProperty; + extra.parseObjectProperty = parseObjectProperty; + extra.parseObjectPropertyKey = parseObjectPropertyKey; + extra.parsePostfixExpression = parsePostfixExpression; + extra.parsePrimaryExpression = parsePrimaryExpression; + extra.parseProgram = parseProgram; + extra.parsePropertyFunction = parsePropertyFunction; + extra.parseRelationalExpression = parseRelationalExpression; + extra.parseStatement = parseStatement; + extra.parseShiftExpression = parseShiftExpression; + extra.parseSwitchCase = parseSwitchCase; + extra.parseUnaryExpression = parseUnaryExpression; + extra.parseVariableDeclaration = parseVariableDeclaration; + extra.parseVariableIdentifier = parseVariableIdentifier; + extra.consumeSemicolon = consumeSemicolon; + + parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression); + parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression); + parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression); + parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression); + parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression); + parseBlock = wrapTracking(extra.parseBlock); + parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements); + parseCallMember = wrapTracking(extra.parseCallMember); + parseCatchClause = wrapTracking(extra.parseCatchClause); + parseComputedMember = wrapTracking(extra.parseComputedMember); + parseConditionalExpression = wrapTracking(extra.parseConditionalExpression); + parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration); + parseEqualityExpression = wrapTracking(extra.parseEqualityExpression); + parseExpression = wrapTracking(extra.parseExpression); + parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration); + parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration); + parseFunctionExpression = wrapTracking(extra.parseFunctionExpression); + parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression); + parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression); + parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression); + parseNewExpression = wrapTracking(extra.parseNewExpression); + parseNonComputedMember = wrapTracking(extra.parseNonComputedMember); + parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty); + parseObjectProperty = wrapTracking(extra.parseObjectProperty); + parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey); + parsePostfixExpression = wrapTracking(extra.parsePostfixExpression); + parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression); + parseProgram = wrapTracking(extra.parseProgram); + parsePropertyFunction = wrapTracking(extra.parsePropertyFunction); + parseRelationalExpression = wrapTracking(extra.parseRelationalExpression); + parseStatement = wrapTracking(extra.parseStatement); + parseShiftExpression = wrapTracking(extra.parseShiftExpression); + parseSwitchCase = wrapTracking(extra.parseSwitchCase); + parseUnaryExpression = wrapTracking(extra.parseUnaryExpression); + parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration); + parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier); + } + + if (extra.errors) { + parseStatement = wrapThrowParseStatement(parseStatement); + parseExpression = wrapThrow(parseExpression); + // this enables 'foo.' to return something + parseNonComputedProperty = wrapThrow(parseNonComputedProperty); + consumeSemicolon = wrapThrow(consumeSemicolon); + } + + if (typeof extra.tokens !== 'undefined') { + extra.advance = advance; + extra.scanRegExp = scanRegExp; + + advance = collectToken; + scanRegExp = collectRegex; + } + } + + function unpatch() { + if (typeof extra.skipComment === 'function') { + skipComment = extra.skipComment; + } + + if (extra.raw) { + createLiteral = extra.createLiteral; + } + + if (extra.range || extra.loc || extra.errors) { + parseAdditiveExpression = extra.parseAdditiveExpression; + parseAssignmentExpression = extra.parseAssignmentExpression; + parseBitwiseANDExpression = extra.parseBitwiseANDExpression; + parseBitwiseORExpression = extra.parseBitwiseORExpression; + parseBitwiseXORExpression = extra.parseBitwiseXORExpression; + parseBlock = extra.parseBlock; + parseFunctionSourceElements = extra.parseFunctionSourceElements; + parseCallMember = extra.parseCallMember; + parseCatchClause = extra.parseCatchClause; + parseComputedMember = extra.parseComputedMember; + parseConditionalExpression = extra.parseConditionalExpression; + parseConstLetDeclaration = extra.parseConstLetDeclaration; + parseEqualityExpression = extra.parseEqualityExpression; + parseExpression = extra.parseExpression; + parseForVariableDeclaration = extra.parseForVariableDeclaration; + parseFunctionDeclaration = extra.parseFunctionDeclaration; + parseFunctionExpression = extra.parseFunctionExpression; + parseLogicalANDExpression = extra.parseLogicalANDExpression; + parseLogicalORExpression = extra.parseLogicalORExpression; + parseMultiplicativeExpression = extra.parseMultiplicativeExpression; + parseNewExpression = extra.parseNewExpression; + parseNonComputedMember = extra.parseNonComputedMember; + parseNonComputedProperty = extra.parseNonComputedProperty; + parseObjectProperty = extra.parseObjectProperty; + parseObjectPropertyKey = extra.parseObjectPropertyKey; + parsePrimaryExpression = extra.parsePrimaryExpression; + parsePostfixExpression = extra.parsePostfixExpression; + parseProgram = extra.parseProgram; + parsePropertyFunction = extra.parsePropertyFunction; + parseRelationalExpression = extra.parseRelationalExpression; + parseStatement = extra.parseStatement; + parseShiftExpression = extra.parseShiftExpression; + parseSwitchCase = extra.parseSwitchCase; + parseUnaryExpression = extra.parseUnaryExpression; + parseVariableDeclaration = extra.parseVariableDeclaration; + parseVariableIdentifier = extra.parseVariableIdentifier; + consumeSemicolon = extra.consumeSemicolon; + } + + if (typeof extra.scanRegExp === 'function') { + advance = extra.advance; + scanRegExp = extra.scanRegExp; + } + } + + function stringToArray(str) { + var length = str.length, + result = [], + i; + for (i = 0; i < length; ++i) { + result[i] = str.charAt(i); + } + return result; + } + + function parse(code, options) { + var program, toString; + + toString = String; + if (typeof code !== 'string' && !(code instanceof String)) { + code = toString(code); + } + + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + length = source.length; + buffer = null; + state = { + allowIn: true, + labelSet: {}, + lastParenthesized: null, + inFunctionBody: false, + inIteration: false, + inSwitch: false + }; + + extra = {}; + if (typeof options !== 'undefined') { + extra.range = (typeof options.range === 'boolean') && options.range; + extra.loc = (typeof options.loc === 'boolean') && options.loc; + extra.raw = (typeof options.raw === 'boolean') && options.raw; + if (typeof options.tokens === 'boolean' && options.tokens) { + extra.tokens = []; + } + if (typeof options.comment === 'boolean' && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === 'boolean' && options.tolerant) { + extra.errors = []; + } + } + + if (length > 0) { + if (typeof source[0] === 'undefined') { + // Try first to convert to a string. This is good as fast path + // for old IE which understands string indexing for string + // literals only and not for string object. + if (code instanceof String) { + source = code.valueOf(); + } + + // Force accessing the characters via an array. + if (typeof source[0] === 'undefined') { + source = stringToArray(code); + } + } + } + + patch(); + try { + program = parseProgram(); + if (typeof extra.comments !== 'undefined') { + program.comments = extra.comments; + } + if (typeof extra.tokens !== 'undefined') { + program.tokens = extra.tokens; + } + if (typeof extra.errors !== 'undefined') { + program.errors = extra.errors; + } + } catch (e) { + throw e; + } finally { + unpatch(); + extra = {}; + } + + return program; + } + + // Sync with package.json. + exports.version = '1.0.0-dev'; + + exports.parse = parse; + + // Deep copy. + exports.Syntax = (function () { + var name, types = {}; + + if (typeof Object.create === 'function') { + types = Object.create(null); + } + + for (name in Syntax) { + if (Syntax.hasOwnProperty(name)) { + types[name] = Syntax[name]; + } + } + + if (typeof Object.freeze === 'function') { + Object.freeze(types); + } + + return types; + }()); + +}(typeof exports === 'undefined' ? (esprima = {}) : exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/scripts/lib/esprima-master/assets/orion/contentassist/esprimaJsContentAssist.js b/scripts/lib/esprima-master/assets/orion/contentassist/esprimaJsContentAssist.js new file mode 100755 index 0000000..63aa7a9 --- /dev/null +++ b/scripts/lib/esprima-master/assets/orion/contentassist/esprimaJsContentAssist.js @@ -0,0 +1,2451 @@ +/******************************************************************************* + * @license + * Copyright (c) 2012 VMware, Inc. All Rights Reserved. + * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE + * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE + * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT. + * You can obtain a current copy of the Eclipse Public License from + * http://www.opensource.org/licenses/eclipse-1.0.php + * + * Contributors: + * Andy Clement (VMware) - initial API and implementation + * Andrew Eisenberg (VMware) - implemented visitor pattern + ******************************************************************************/ + +/*global define require eclipse esprima window */ +define("plugins/esprima/esprimaJsContentAssist", ["plugins/esprima/esprimaVisitor", "plugins/esprima/types", "plugins/esprima/proposalUtils"], + function(mVisitor, mTypes, proposalUtils, scriptedLogger) { + + /** @type {function(obj):Boolean} a safe way of checking for arrays */ + var isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(ary) { + return Object.prototype.toString.call(ary) === '[object Array]'; + }; + } + + var RESERVED_WORDS = { + "break" : true, "case" : true, "catch" : true, "continue" : true, "debugger" : true, "default" : true, "delete" : true, "do" : true, "else" : true, "finally" : true, + "for" : true, "function" : true, "if" : true, "in" : true, "instanceof" : true, "new" : true, "return" : true, "switch" : true, "this" : true, "throw" : true, "try" : true, "typeof" : true, + "var" : true, "void" : true, "while" : true, "with" : true + }; + function isReserverdWord(name) { + return RESERVED_WORDS[name] === true; + } + + /** + * @param {String} char a string of at least one char14acter + * @return {boolean} true iff uppercase ascii character + */ + function isUpperCaseChar(c) { + if (c.length < 1) { + return false; + } + var charCode = c.charCodeAt(0); + if (isNaN(charCode)) { + return false; + } + return charCode >= 65 && charCode <= 90; + } + + /** + * finds the right-most segment of a dotted MemberExpression + * if it is an identifier, or null otherwise + * @return {{name:String}} + */ + function findRightMost(node) { + if (!node) { + return null; + } else if (node.type === "Identifier") { + return node; + } else if (node.type === "MemberExpression") { + if (node.computed) { + if (node.property.type === "Literal" && typeof node.property.value === "string") { + return node.property; + } else { + // an array access + return node; + } + } else { + return findRightMost(node.property); + } + } else if (node.type === "ArrayExpression") { + return node; + } else { + return null; + } + } + + /** + * Recursively generates a name based on the given expression + * @param {{type:String,name:String}} node + * @return {String} + */ + function findDottedName(node) { + if (!node) { + return ""; + } else if (node.type === "Identifier") { + return node.name; + } else if (node.type === "MemberExpression") { + var left = findDottedName(node.object); + var right = findDottedName(node.property); + if (left.length > 0 && right.length > 0) { + return left + "." + right; + } + return left + right; + } else if (node.type === "CallExpression") { + return findDottedName(node.callee); + } else { + return ""; + } + } + + /** + * Convert an array of parameters into a string and also compute linked editing positions + * @param {String} name name of the function + * @param {String} type the type of the function using the following structure '?Type:arg1,arg2,...' + * @param {Number} offset offset + * @return {{ completion:String, positions:Array. }} + */ + function calculateFunctionProposal(name, type, offset) { + var paramsOffset = mTypes.findReturnTypeEnd(type), paramsStr, params; + paramsStr = paramsOffset > 0 ? type.substring(paramsOffset+1) : ""; + params = paramsStr.split(","); + if (!paramsStr || params.length === 0) { + return {completion: name + "()", positions:null}; + } + var positions = []; + var completion = name + '('; + var plen = params.length; + for (var p = 0; p < plen; p++) { + if (p > 0) { + completion += ', '; + } + var argName; + if (typeof params[p] === "string") { + // need this because jslintworker.js augments the String prototype with a name() function + // don't want confusion + argName = params[p]; + var slashIndex = argName.indexOf('/'); + if (slashIndex > 0) { + argName = argName.substring(0, slashIndex); + } + } else if (params[p].name) { + argName = params[p].name(); + } else { + argName = params[p]; + } + positions.push({offset:offset+completion.length+1, length: argName.length}); + completion += argName; + } + completion += ')'; + return {completion: completion, positions: positions.length === 0 ? null : positions}; + } + + /** + * checks that offset overlaps with the given range + * Since esprima ranges are zero-based, inclusive of + * the first char and exclusive of the last char, must + * use a +1 at the end. + * eg- (^ is the line start) + * ^x ---> range[0,0] + * ^ xx ---> range[2,3] + */ + function inRange(offset, range, includeEdge) { + return range[0] <= offset && (includeEdge ? range[1] >= offset : range[1] > offset); + } + /** + * checks that offset is before the range + * @return Boolean + */ + function isBefore(offset, range) { + if (!range) { + return true; + } + return offset < range[0]; + } + + /** + * Determines if the offset is inside this member expression, but after the '.' and before the + * start of the property. + * eg, the following returns true: + * foo .^bar + * foo . ^ bar + * The following returns false: + * foo ^. bar + * foo . b^ar + * @return Boolean + */ + function afterDot(offset, memberExpr, contents) { + // check for broken AST + var end; + if (memberExpr.property) { + end = memberExpr.property.range[0]; + } else { + // no property expression, use the end of the memberExpr as the end to look at + // in this case assume that the member expression ends just after the dot + // this allows content assist invocations to work on the member expression when there + // is no property + end = memberExpr.range[1] + 2; + } + // we are not considered "after" the dot if the offset + // overlaps with the property expression or if the offset is + // after the end of the member expression + if (!inRange(offset-1, memberExpr.range) || + inRange(offset-1, memberExpr.object.range) || + offset > end) { + return false; + } + + var dotLoc = memberExpr.object.range[1]; + while (contents.charAt(dotLoc) !== "." && dotLoc < end) { + dotLoc++; + } + + if (contents.charAt(dotLoc) !== ".") { + return false; + } + + return dotLoc < offset; + } + + /** + * @return "top" if we are at a start of a new expression fragment (eg- at an empty line, + * or a new parameter). "member" if we are after a dot in a member expression. false otherwise + * @return {Boolean|String} + */ + function shouldVisit(root, offset, prefix, contents) { + /** + * A visitor that finds the parent stack at the given location + * @param node the AST node being visited + * @param parents stack of parent nodes for the current node + * @param isInitialVisit true iff this is the first visit of the node, false if this is + * the end visit of the node + */ + var findParent = function(node, parents, isInitialVisit) { + // extras prop is where we stuff everything that we have added + if (!node.extras) { + node.extras = {}; + } + + if (!isInitialVisit) { + + // if we have reached the end of an inRange block expression then + // this means we are completing on an empty expression + if (node.type === "Program" || (node.type === "BlockStatement") && + inRange(offset, node.range)) { + throw "done"; + } + + parents.pop(); + // return value is ignored + return false; + } + + // the program node is always in range even if the range numbers do not line up + if ((node.range && inRange(offset-1, node.range)) || node.type === "Program") { + if (node.type === "Identifier") { + throw "done"; + } + parents.push(node); + if ((node.type === "FunctionDeclaration" || node.type === "FunctionExpression") && + node.nody && isBefore(offset, node.body.range)) { + // completion occurs on the word "function" + throw "done"; + } + // special case where we are completing immediately after a '.' + if (node.type === "MemberExpression" && !node.property && afterDot(offset, node, contents)) { + throw "done"; + } + return true; + } else { + return false; + } + }; + var parents = []; + try { + mVisitor.visit(root, parents, findParent, findParent); + } catch (done) { + if (done !== "done") { + // a real error + throw(done); + } + } + + // determine if we need to defer infering the enclosing function block + var toDefer; + if (parents && parents.length) { + var parent = parents.pop(); + for (var i = 0; i < parents.length; i++) { + if ((parents[i].type === "FunctionDeclaration" || parents[i].type === "FunctionExpression") && + // don't defer if offset is over the function name + !(parents[i].id && inRange(offset, parents[i].id.range, true))) { + toDefer = parents[i]; + break; + } + + } + + if (parent.type === "MemberExpression") { + if (parent.property && inRange(offset-1, parent.property.range)) { + // on the right hand side of a property, eg: foo.b^ + return { kind : "member", toDefer : toDefer }; + } else if (inRange(offset-1, parent.range) && afterDot(offset, parent, contents)) { + // on the right hand side of a dot with no text after, eg: foo.^ + return { kind : "member", toDefer : toDefer }; + } + } else if (parent.type === "Program" || parent.type === "BlockStatement") { + // completion at a new expression + if (!prefix) { + } + } else if (parent.type === "VariableDeclarator" && (!parent.init || isBefore(offset, parent.init.range))) { + // the name of a variable declaration + return false; + } else if ((parent.type === "FunctionDeclaration" || parent.type === "FunctionExpression") && + isBefore(offset, parent.body.range)) { + // a function declaration + return false; + } + } + return { kind : "top", toDefer : toDefer }; + } + + /** + * finds the final return statement of a function declaration + * @param node an ast statement node + * @return the lexically last ReturnStatment AST node if there is one, else + * null if there is no return statement + */ + function findReturn(node) { + if (!node) { + return null; + } + var type = node.type, maybe, i, last; + // since we are finding the last return statement, start from the end + switch(type) { + case "BlockStatement": + if (node.body && node.body.length > 0) { + last = node.body[node.body.length-1]; + if (last.type === "ReturnStatement") { + return last; + } else { + return findReturn(last); + } + } + return null; + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + case "ForInStatement": + case "CatchClause": + + return findReturn(node.body); + case "IfStatement": + maybe = findReturn(node.alternate); + if (!maybe) { + maybe = findReturn(node.consequent); + } + return maybe; + case "TryStatement": + maybe = findReturn(node.finalizer); + var handlers = node.handlers; + if (!maybe && handlers) { + // start from the last handler + for (i = handlers.length-1; i >= 0; i--) { + maybe = findReturn(handlers[i]); + if (maybe) { + break; + } + } + } + if (!maybe) { + maybe = findReturn(node.block); + } + return maybe; + case "SwitchStatement": + var cases = node.cases; + if (cases) { + // start from the last handler + for (i = cases.length-1; i >= 0; i--) { + maybe = findReturn(cases[i]); + if (maybe) { + break; + } + } + } + return maybe; + case "SwitchCase": + if (node.consequent && node.consequent.length > 0) { + last = node.consequent[node.consequent.length-1]; + if (last.type === "ReturnStatement") { + return last; + } else { + return findReturn(last); + } + } + return null; + + case "ReturnStatement": + return node; + default: + // don't visit nested functions + // expression statements, variable declarations, + // or any other kind of node + return null; + } + } + + /** + * updates a function type to include a new return type. + * function types are specified like this: ?returnType:[arg-n...] + * return type is the name of the return type, arg-n is the name of + * the nth argument. + */ + function updateReturnType(originalFunctionType, newReturnType) { + if (! originalFunctionType) { + // not a valid function type + return newReturnType; + } + + var firstChar = originalFunctionType.charAt(0); + if (firstChar !== "?" && firstChar !== "*") { + // not a valid function type + return newReturnType; + } + + var end = mTypes.findReturnTypeEnd(originalFunctionType); + if (end < 0) { + // not a valid function type + return newReturnType; + } + return firstChar + newReturnType + originalFunctionType.substring(end); + } + /** + * checks to see if this file looks like an AMD module + * Assumes that there are one or more calls to define at the top level + * and the first statement is a define call + * @return true iff there is a top-level call to 'define' + */ + function checkForAMD(node) { + var body = node.body; + if (body && body.length >= 1 && body[0]) { + if (body[0].type === "ExpressionStatement" && + body[0].expression && + body[0].expression.type === "CallExpression" && + body[0].expression.callee.name === "define") { + + // found it. + return body[0].expression; + } + } + return null; + } + /** + * checks to see if this file looks like a wrapped commonjs module + * Assumes that there are one or more calls to define at the top level + * and the first statement is a define call + * @return true iff there is a top-level call to 'define' + */ + function checkForCommonjs(node) { + var body = node.body; + if (body && body.length >= 1) { + for (var i = 0; i < body.length; i++) { + if (body[i] && + body[i].type === "ExpressionStatement" && + body[i].expression && + body[i].expression.type === "CallExpression" && + body[i].expression.callee.name === "define") { + + var callee = body[i].expression; + if (callee["arguments"] && + callee["arguments"].length === 1 && + callee["arguments"][0].type === "FunctionExpression" && + callee["arguments"][0].params.length === 3) { + + var params = callee["arguments"][0].params; + if (params[0].name === "require" && + params[1].name === "exports" && + params[2].name === "module") { + + // found it. + return body[i].expression; + } + } + } + } + } + return null; + } + + /** + * if this method call ast node is a call to require with a single string constant + * argument, then look that constant up in the indexer to get a summary + * if a summary is found, then apply it to the current scope + */ + function extractRequireModule(call, env) { + if (!env.indexer) { + return; + } + if (call.type === "CallExpression" && call.callee.type === "Identifier" && + call.callee.name === "require" && call["arguments"].length === 1) { + + var arg = call["arguments"][0]; + if (arg.type === "Literal" && typeof arg.value === "string") { + // we're in business + var summary = env.indexer.retrieveSummary(arg.value); + if (summary) { + var typeName; + var mergeTypeName; + if (typeof summary.provided === "string") { + mergeTypeName = typeName = summary.provided; + } else { + // module provides a composite type + // must create a type to add the summary to + mergeTypeName = typeName = env.newScope(); + env.popScope(); + } + env.mergeSummary(summary, mergeTypeName); + return typeName; + } + } + } + + return; + } + + /** + * checks to see if this function is a module definition + * and if so returns an array of module definitions + * + * if this is not a module definition, then just return an array of Object for each typ + */ + function findModuleDefinitions(fnode, env) { + var paramTypes = [], params = fnode.params, i; + if (params.length > 0) { + if (!fnode.extras) { + fnode.extras = {}; + } + if (env.indexer && fnode.extras.amdDefn) { + var args = fnode.extras.amdDefn["arguments"]; + // the function definition must be the last argument of the call to define or require + if (args.length > 1 && args[args.length-1] === fnode) { + // the module names could be the first or second argument + var moduleNames = null; + if (args.length === 3 && args[0].type === "Literal" && args[1].type === "ArrayExpression") { + moduleNames = args[1].elements; + } else if (args.length === 2 && args[0].type === "ArrayExpression") { + moduleNames = args[0].elements; + } + if (moduleNames) { + for (i = 0; i < params.length; i++) { + if (i < moduleNames.length && moduleNames[i].type === "Literal") { + // resolve the module name from the indexer + var summary = env.indexer.retrieveSummary(moduleNames[i].value); + if (summary) { + var typeName; + var mergeTypeName; + if (typeof summary.provided === "string") { + mergeTypeName = typeName = summary.provided; + } else { + // module provides a composite type + // must create a type to add the summary to + mergeTypeName = typeName = env.newScope(); + env.popScope(); + } + env.mergeSummary(summary, mergeTypeName); + paramTypes.push(typeName); + } else { + paramTypes.push(env.newFleetingObject()); + } + } else { + paramTypes.push("Object"); + } + } + } + } + } + } + if (paramTypes.length === 0) { + for (i = 0; i < params.length; i++) { + paramTypes.push(env.newFleetingObject()); + } + } + return paramTypes; + } + + + /** + * Finds the closest doc comment to this node + * @param {{range:Array.}} node + * @param {Array.<{range:Array.}>} doccomments + * @return {{value:String,range:Array.}} + */ + function findAssociatedCommentBlock(node, doccomments) { + // look for closest doc comment that is before the start of this node + // just shift all the other ones + var candidate; + while (doccomments.length > 0 && doccomments[0].range[0] < node.range[0]) { + candidate = doccomments.shift(); + } + return candidate || { value : null }; + } + + + /** + * Extracts all doccomments that fall inside the given range. + * Side effect is to remove the array elements + * @param Array.<{range:Array.> doccomments + * @param Array. range + * @return {{value:String,range:Array.}} array elements that are removed + */ + function extractDocComments(doccomments, range) { + var start = 0, end = 0, i, docStart, docEnd; + for (i = 0; i < doccomments.length; i++) { + docStart = doccomments[i].range[0]; + docEnd = doccomments[i].range[1]; + if (!isBefore(docStart, range) || !isBefore(docEnd, range)) { + break; + } + } + + if (i < doccomments.length) { + start = i; + for (i = i; i < doccomments.length; i++) { + docStart = doccomments[i].range[0]; + docEnd = doccomments[i].range[1]; + if (!inRange(docStart, range, true) || !inRange(docEnd, range, true)) { + break; + } + } + end = i; + } + + return doccomments.splice(start, end-start); + } + + /** + * This function takes the current AST node and does the first inferencing step for it. + * @param node the AST node to visit + * @param env the context for the visitor. See computeProposals below for full description of contents + */ + function inferencer(node, env) { + var type = node.type, name, i, property, params, newTypeName, jsdocResult, jsdocType; + + // extras prop is where we stuff everything that we have added + if (!node.extras) { + node.extras = {}; + } + + switch(type) { + case "Program": + // check for module kind + env.commonjsModule = checkForCommonjs(node); + if (!env.commonjsModule) { + // can't be both amd and commonjs + env.amdModule = checkForAMD(node); + } + break; + case "BlockStatement": + node.extras.inferredType = env.newScope(); + if (node.extras.stop) { + // this BlockStatement inferencing is deferred until after the rest of the file is inferred + inferencerPostOp(node, env); + delete node.extras.stop; + return false; + } + break; + case "Literal": + break; + case "ArrayExpression": + node.extras.inferredType = "Array"; + break; + case "ObjectExpression": + if (node.extras.fname) { + // this object expression is contained inside another object expression + env.pushName(node.extras.fname); + } + + // for object literals, create a new object type so that we can stuff new properties into it. + // we might be able to do better by walking into the object and inferring each RHS of a + // key-value pair + newTypeName = env.newObject(null, node.range); + node.extras.inferredType = newTypeName; + for (i = 0; i < node.properties.length; i++) { + property = node.properties[i]; + // only remember if the property is an identifier + if (property.key && property.key.name) { + // first just add as an object property (or use jsdoc if exists). + // after finishing the ObjectExpression, go and update + // all of the variables to reflect their final inferred type + var docComment = findAssociatedCommentBlock(property.key, env.comments); + jsdocResult = mTypes.parseJSDocComment(docComment); + jsdocType = mTypes.convertJsDocType(jsdocResult.type, env); + var keyType = jsdocType ? jsdocType : "Object"; + env.addVariable(property.key.name, node, keyType, property.key.range, docComment.range); + if (!property.key.extras) { + property.key.extras = {}; + } + property.key.extras.associatedComment = docComment; + // remember that this is the LHS so that we don't add the identifier to global scope + property.key.extras.isLHS = property.key.extras.isDecl = true; + + if (property.value.type === "FunctionExpression" || property.value.type === "ObjectExpression") { + if (!property.value.extras) { + property.value.extras = {}; + } + // RHS is a function, remember the name in case it is a constructor + property.value.extras.fname = property.key.name; + property.value.extras.cname = env.getQualifiedName() + property.key.name; + + if (property.value.type === "FunctionExpression") { + // now remember the jsdocResult so it doesn't need to be recomputed + property.value.extras.jsdocResult = jsdocResult; + } + } + } + } + break; + case "FunctionDeclaration": + case "FunctionExpression": + var nameRange; + if (node.id) { + // true for function declarations + name = node.id.name; + nameRange = node.id.range; + } else if (node.extras.fname) { + // true for rhs of assignment to function expression + name = node.extras.fname; + nameRange = node.range; + } + params = []; + if (node.params) { + for (i = 0; i < node.params.length; i++) { + params[i] = node.params[i].name; + } + } + + if (node.extras.jsdocResult) { + jsdocResult = node.extras.jsdocResult; + docComment = { range : null }; + } else { + docComment = node.extras.associatedComment || findAssociatedCommentBlock(node, env.comments); + jsdocResult = mTypes.parseJSDocComment(docComment); + } + + // assume that function name that starts with capital is + // a constructor + var isConstuctor; + if (name && node.body && isUpperCaseChar(name)) { + if (node.extras.cname) { + // RHS of assignment + name = node.extras.cname; + } + // create new object so that there is a custom "this" + newTypeName = env.newObject(name, node.range); + isConstuctor = true; + } else { + var jsdocReturn = mTypes.convertJsDocType(jsdocResult.rturn, env); + if (jsdocReturn) { + // keep track of the return type for the way out + node.extras.jsdocReturn = jsdocReturn; + newTypeName = jsdocReturn; + node.extras.inferredType = jsdocReturn; + } else { + // temporarily use "undefined" as type, but this may change once we + // walk through to get to a return statement + newTypeName = "undefined"; + } + isConstuctor = false; + } + if (!node.body.extras) { + node.body.extras = {}; + } + node.body.extras.isConstructor = isConstuctor; + + // add parameters to the current scope + var paramTypeSigs = [], paramSigs = []; + if (params.length > 0) { + var moduleDefs = findModuleDefinitions(node, env); + for (i = 0; i < params.length; i++) { + // choose jsdoc tags over module definitions + var jsDocParam = jsdocResult.params[params[i]]; + var typeName = null; + if (jsDocParam) { + typeName = mTypes.convertJsDocType(jsDocParam, env); + } + if (!typeName) { + typeName = moduleDefs[i]; + } + paramTypeSigs.push(typeName); + paramSigs.push(params[i] + "/" + typeName); + } + } + + + var functionTypeName = (isConstuctor ? "*" : "?") + newTypeName + ":" + paramSigs.join(","); + if (isConstuctor) { + env.createConstructor(functionTypeName, newTypeName); + // assume that constructor will be available from global scope using qualified name + // this is not correct in all cases + env.addOrSetGlobalVariable(name, functionTypeName, nameRange, docComment.range); + } + + node.extras.inferredType = functionTypeName; + + if (name && !isBefore(env.offset, node.range)) { + // if we have a name, then add it to the scope + env.addVariable(name, node.extras.target, functionTypeName, nameRange, docComment.range); + } + + // now add the scope for inside the function + env.newScope(); + env.addVariable("arguments", node.extras.target, "Arguments", node.range); + + + // now determine if we need to add 'this'. If this function has an appliesTo, the we know it is being assigned as a property onto something else + // the 'something else' is the 'this' type. + // eg- var obj={};var obj.fun=function() { ... }; + var appliesTo = node.extras.appliesTo; + if (appliesTo) { + var appliesToOwner = appliesTo.extras.target; + if (appliesToOwner) { + var ownerTypeName = env.scope(appliesToOwner); + // for the special case of adding to the prototype, we want to make sure that we also add to the 'this' of + // the instantiated types + if (mTypes.isPrototype(ownerTypeName)) { + ownerTypeName = mTypes.extractReturnType(ownerTypeName); + } + env.addVariable("this", node.extras.target, ownerTypeName, nameRange, docComment.range); + } + } + + // add variables for all parameters + for (i = 0; i < params.length; i++) { + env.addVariable(params[i], node.extras.target, paramTypeSigs[i], node.params[i].range); + } + break; + case "VariableDeclarator": + if (node.id.name) { + // remember that the identifier is an LHS + // so, don't create a type for it + if (!node.id.extras) { + node.id.extras = {}; + } + node.id.extras.isLHS = node.id.extras.isDecl = true; + if (node.init && !node.init.extras) { + node.init.extras = {}; + } + if (node.init && node.init.type === "FunctionExpression") { + // RHS is a function, remember the name in case it is a constructor + node.init.extras.fname = node.id.name; + node.init.extras.cname = env.getQualifiedName() + node.id.name; + node.init.extras.fnameRange = node.id.range; + } else { + // not the RHS of a function, check for jsdoc comments + var docComment = findAssociatedCommentBlock(node, env.comments); + jsdocResult = mTypes.parseJSDocComment(docComment); + jsdocType = mTypes.convertJsDocType(jsdocResult.type, env); + node.extras.docRange = docComment.range; + if (jsdocType) { + node.extras.inferredType = jsdocType; + node.extras.jsdocType = jsdocType; + env.addVariable(node.id.name, node.extras.target, jsdocType, node.id.range, docComment.range); + } + } + } + env.pushName(node.id.name); + break; + case "AssignmentExpression": + var rightMost = findRightMost(node.left); + var qualName = env.getQualifiedName() + findDottedName(node.left); + if (rightMost && (rightMost.type === "Identifier" || rightMost.type === "Literal")) { + if (!rightMost.extras) { + rightMost.extras = {}; + } + if (node.right.type === "FunctionExpression") { + // RHS is a function, remember the name in case it is a constructor + if (!node.right.extras) { + node.right.extras = {}; + } + node.right.extras.appliesTo = rightMost; + node.right.extras.fname = rightMost.name; + node.right.extras.cname = qualName; + node.right.extras.fnameRange = rightMost.range; + + if (!node.left.extras) { + node.left.extras = {}; + } + } + var docComment = findAssociatedCommentBlock(node, env.comments); + jsdocResult = mTypes.parseJSDocComment(docComment); + jsdocType = mTypes.convertJsDocType(jsdocResult.type, env); + node.extras.docRange = docComment.range; + if (jsdocType) { + node.extras.inferredType = jsdocType; + node.extras.jsdocType = jsdocType; + env.addVariable(rightMost.name, node.extras.target, jsdocType, rightMost.range, docComment.range); + } + } + env.pushName(qualName); + break; + case "CatchClause": + // create a new scope for the catch parameter + node.extras.inferredType = env.newScope(); + if (node.param) { + if (!node.param.extras) { + node.param.extras = {}; + } + node.param.extras.inferredType = "Error"; + env.addVariable(node.param.name, node.extras.target, "Error", node.param.range); + } + break; + case "MemberExpression": + if (node.property) { + if (!node.computed || // like this: foo.at + (node.computed && node.property.type === "Literal" && typeof node.property.value === "string")) { // like this: foo['at'] + + // keep track of the target of the property expression + // so that its type can be used as the seed for finding properties + if (!node.property.extras) { + node.property.extras = {}; + } + node.property.extras.target = node.object; + } else { // like this: foo[at] or foo[0] + // do nothing + } + } + break; + case "CallExpression": + if (node.callee.name === "define" || node.callee.name === "require") { + // check for AMD definition + var args = node["arguments"]; + if (args.length > 1 && + args[args.length-1].type === "FunctionExpression" && + args[args.length-2].type === "ArrayExpression") { + + // assume definition + if (!args[args.length-1].extras) { + args[args.length-1].extras = {}; + } + args[args.length-1].extras.amdDefn = node; + } + } + break; + } + + // defer the inferencing of the function's children containing the offset. + if (node === env.defer) { + node.extras.associatedComment = findAssociatedCommentBlock(node, env.comments); + node.extras.inferredType = node.extras.inferredType || "Object"; // will be filled in later + // need to remember the scope to place this function in for later + node.extras.scope = env.scope(node.extras.target); + + // need to infer the body of this function later + node.body.extras.stop = true; + } + + return true; + } + + /** + * called as the post operation for the proposalGenerator visitor. + * Finishes off the inferencing and adds all proposals + */ + function inferencerPostOp(node, env) { + var type = node.type, name, inferredType, newTypeName, rightMost, kvps, i; + + switch(type) { + case "Program": + if (env.defer) { + // finally, we can infer the deferred target function + + // now use the comments that we deferred until later + env.comments = env.deferredComments; + + var defer = env.defer; + env.defer = null; + env.targetType = null; + env.pushScope(defer.extras.scope); + mVisitor.visit(defer.body, env, inferencer, inferencerPostOp); + env.popScope(); + } + + // in case we haven't stored target yet, do so now. + env.storeTarget(); + + // TODO FIXADE for historical reasons we end visit by throwing exception. Should chamge + throw env.targetType; + case "BlockStatement": + case "CatchClause": + if (inRange(env.offset, node.range)) { + // if we've gotten here and we are still in range, then + // we are completing as a top-level entity with no prefix + env.storeTarget(); + } + + env.popScope(); + break; + case "MemberExpression": + if (afterDot(env.offset, node, env.contents)) { + // completion after a dot with no prefix + env.storeTarget(env.scope(node.object)); + } + + // for arrays, inferred type is the dereferncing of the array type + // for non-arrays inferred type is the type of the property expression + if (mTypes.isArrayType(node.object.extras.inferredType) && node.computed) { + // inferred type of expression is the type of the dereferenced array + node.extras.inferredType = mTypes.extractArrayParameterType(node.object.extras.inferredType); + } else if (node.computed && node.property && node.property.type !== "Literal") { + // we don't infer parameterized objects, but we have something like this: 'foo[at]' just assume type is object + node.extras.inferredType = "Object"; + } else { + // a regular member expression: foo.bar or foo['bar'] + // node.propery will be null for mal-formed asts + node.extras.inferredType = node.property ? node.property.extras.inferredType : node.object.extras.inferredType; + } + break; + case "CallExpression": + // first check to see if this is a require call + var fnType = extractRequireModule(node, env); + + // otherwise, apply the function + if (!fnType) { + fnType = node.callee.extras.inferredType; + fnType = mTypes.extractReturnType(fnType); + } + node.extras.inferredType = fnType; + break; + case "NewExpression": + // FIXADE we have a problem here. + // constructors that are called like this: new foo.Bar() should have an inferred type of foo.Bar, + // This ensures that another constructor new baz.Bar() doesn't conflict. However, + // we are only taking the final prefix and assuming that it is unique. + node.extras.inferredType = mTypes.extractReturnType(node.callee.extras.inferredType); + break; + case "ObjectExpression": + // now that we know all the types of the values, use that to populate the types of the keys + kvps = node.properties; + for (i = 0; i < kvps.length; i++) { + if (kvps[i].hasOwnProperty("key")) { + // only do this for keys that are identifiers + // set the proper inferred type for the key node + // and also update the variable + name = kvps[i].key.name; + if (name) { + // now check for the special case where the rhs value is an identifier. + // we want to shortcut the navigation and go through to the definition + // of the identifier, BUT only do this if the identifier points to a function + // and the key and value names match. + var range = null; + if (name === kvps[i].value.name) { + var def = env.lookupName(kvps[i].value.name, null, false, true); + if (def && def.range && (mTypes.isFunctionOrConstructor(def.typeName))) { + range = def.range; + } + } + if (!range) { + range = kvps[i].key.range; + } + + inferredType = kvps[i].value.extras.inferredType; + var docComment = kvps[i].key.extras.associatedComment; + env.addVariable(name, node, inferredType, range, docComment.range); + if (inRange(env.offset-1, kvps[i].key.range)) { + // We found it! rmember for later, but continue to the end of file anyway + env.storeTarget(env.scope(node)); + } + } + } + } + if (node.extras.fname) { + // this object expression is contained inside another object expression + env.popName(); + } + env.popScope(); + break; + case "LogicalExpression": + case "BinaryExpression": + switch (node.operator) { + case '+': + // special case: if either side is a string, then result is a string + if (node.left.extras.inferredType === "String" || + node.right.extras.inferredType === "String") { + + node.extras.inferredType = "String"; + } else { + node.extras.inferredType = "Number"; + } + break; + case '-': + case '/': + case '*': + case '%': + case '&': + case '|': + case '^': + case '<<': + case '>>': + case '>>>': + // Numeric and bitwise operations always return a number + node.extras.inferredType = "Number"; + break; + case '&&': + case '||': + // will be the type of the left OR the right + // for now arbitrarily choose the left + node.extras.inferredType = node.left.extras.inferredType; + break; + + case '!==': + case '!=': + case '===': + case '==': + case '<': + case '<=': + case '>': + case '>=': + node.extras.inferredType = "Boolean"; + break; + + + default: + node.extras.inferredType = "Object"; + } + break; + case "UpdateExpression": + case "UnaryExpression": + if (node.operator === '!') { + node.extras.inferredType = "Boolean"; + } else { + // includes all unary operations and update operations + // ++ -- - and ~ + node.extras.inferredType = "Number"; + } + break; + case "FunctionDeclaration": + case "FunctionExpression": + env.popScope(); + if (node.body) { + var fnameRange; + if (node.body.extras.isConstructor) { + if (node.id) { + fnameRange = node.id.range; + } else { + fnameRange = node.extras.fnameRange; + } + + // an extra scope was created for the implicit 'this' + env.popScope(); + + // now add a reference to the constructor + env.addOrSetVariable(mTypes.extractReturnType(node.extras.inferredType), node.extras.target, node.extras.inferredType, fnameRange); + } else { + // a regular function. if we don't already know the jsdoc return, + // try updating to a more explicit return type + if (!node.extras.jsdocReturn) { + var returnStatement = findReturn(node.body); + var returnType; + if (returnStatement && returnStatement.extras && returnStatement.extras.inferredType) { + returnType = returnStatement.extras.inferredType; + } else { + returnType = "undefined"; + } + node.extras.inferredType = updateReturnType(node.extras.inferredType, returnType); + } + // if there is a name, then update that as well + var fname; + if (node.id) { + // true for function declarations + fname = node.id.name; + fnameRange = node.id.range; + } else if (node.extras.appliesTo) { + // true for rhs of assignment to function expression + fname = node.extras.fname; + fnameRange = node.extras.fnameRange; + } + if (fname) { + env.addOrSetVariable(fname, node.extras.target, node.extras.inferredType, fnameRange); + } + } + } + break; + case "VariableDeclarator": + if (node.init) { + inferredType = node.init.extras.inferredType; + } else { + inferredType = env.newFleetingObject(); + } + node.id.extras.inferredType = inferredType; + if (!node.extras.jsdocType) { + node.extras.inferredType = inferredType; + env.addVariable(node.id.name, node.extras.target, inferredType, node.id.range, node.extras.docRange); + } + if (inRange(env.offset-1, node.id.range)) { + // We found it! rmember for later, but continue to the end of file anyway + env.storeTarget(env.scope(node.id.extras.target)); + } + env.popName(); + break; + + case "Property": + node.extras.inferredType = node.key.extras.inferredType = node.value.extras.inferredType; + break; + + case "AssignmentExpression": + if (node.extras.jsdocType) { + // use jsdoc instead of whatever we have inferred + inferredType = node.extras.jsdocType; + } else if (node.operator === '=') { + // standard assignment + inferredType = node.right.extras.inferredType; + } else { + // +=, -=, *=, /=, >>=, <<=, >>>=, &=, |=, or ^=. + if (node.operator === '+=' && node.left.extras.inferredType === 'String') { + inferredType = "String"; + } else { + inferredType = "Number"; + } + } + + node.extras.inferredType = inferredType; + // when we have 'this.that.theOther.f' need to find the right-most identifier + rightMost = findRightMost(node.left); + if (rightMost && (rightMost.type === "Identifier" || rightMost.type === "Literal")) { + name = rightMost.name ? rightMost.name : rightMost.value; + rightMost.extras.inferredType = inferredType; + env.addOrSetVariable(name, rightMost.extras.target, inferredType, rightMost.range, node.extras.docRange); + if (inRange(env.offset-1, rightMost.range)) { + // We found it! remember for later, but continue to the end of file anyway + env.storeTarget(env.scope(rightMost.extras.target)); + } + } else { + // might be an assignment to an array, like: + // foo[at] = bar; + if (node.left.computed) { + rightMost = findRightMost(node.left.object); + if (rightMost && !(rightMost.type === 'Identifier' && rightMost.name === 'prototype')) { + // yep...now go and update the type of the array + // (also don't turn refs to prototype into an array. this breaks things) + var arrayType = mTypes.parameterizeArray(inferredType); + node.left.extras.inferredType = inferredType; + node.left.object.extras.inferredType = arrayType; + env.addOrSetVariable(rightMost.name, rightMost.extras.target, arrayType, rightMost.range, node.extras.docRange); + } + } + } + env.popName(); + break; + case 'Identifier': + name = node.name; + newTypeName = env.lookupName(name, node.extras.target); + if (newTypeName && !node.extras.isDecl) { + // name already exists but we are redeclaring it and so not being overridden + node.extras.inferredType = newTypeName; + if (inRange(env.offset, node.range, true)) { + // We found it! rmember for later, but continue to the end of file anyway + env.storeTarget(env.scope(node.extras.target)); + } + } else if (!node.extras.isLHS) { + if (!inRange(env.offset, node.range, true) && !isReserverdWord(name)) { + // we have encountered a read of a variable/property that we have never seen before + + if (node.extras.target) { + // this is a property on an object. just add to the target + env.addVariable(name, node.extras.target, env.newFleetingObject(), node.range); + } else { + // add as a global variable + node.extras.inferredType = env.addOrSetGlobalVariable(name, null, node.range).typeName; + } + } else { + // We found it! rmember for later, but continue to the end of file anyway + env.storeTarget(env.scope(node.extras.target)); + } + } else { + // if this node is an LHS of an assign, don't store target yet, + // we need to first apply the RHS before applying. + // This will happen in the enclosing assignment or variable declarator + } + break; + case "ThisExpression": + node.extras.inferredType = env.lookupName("this"); + if (inRange(env.offset-1, node.range)) { + // We found it! rmember for later, but continue to the end of file anyway + env.storeTarget(env.scope()); + } + break; + case "ReturnStatement": + if (node.argument) { + node.extras.inferredType = node.argument.extras.inferredType; + } + break; + + case "Literal": + if (node.extras.target && typeof node.value === "string") { + // we are inside a computed member expression. + // find the type of the property referred to if exists + name = node.value; + newTypeName = env.lookupName(name, node.extras.target); + node.extras.inferredType = newTypeName; + } else if (node.extras.target && typeof node.value === "number") { + // inside of an array access + node.extras.inferredType = "Number"; + } else { + var oftype = (typeof node.value); + node.extras.inferredType = oftype[0].toUpperCase() + oftype.substring(1, oftype.length); + } + break; + + case "ConditionalExpression": + var target = node.consequent ? node.consequent : node.alternate; + if (target) { + node.extras.inferredType = target.extras.inferredType; + } + break; + + case "ArrayExpression": + // parameterize this array by the type of its first non-null element + if (node.elements) { + for (i = 0; i < node.elements.length; i++) { + if (node.elements[i]) { + node.extras.inferredType = mTypes.parameterizeArray(node.elements[i].extras.inferredType); + } + } + } + } + + if (!node.extras.inferredType) { + node.extras.inferredType = "Object"; + } + } + + + /** + * add variable names from inside a lint global directive + */ + function addLintGlobals(env, lintOptions) { + var i, globName; + if (lintOptions && isArray(lintOptions.global)) { + for (i = 0; i < lintOptions.global.length; i++) { + globName = lintOptions.global[i]; + if (!env.lookupName(globName)) { + env.addOrSetVariable(globName); + } + } + } + var comments = env.comments; + if (comments) { + for (i = 0; i < comments.length; i++) { + var range = comments[i].range; + if (comments[i].type === "Block" && comments[i].value.substring(0, "global".length) === "global") { + var globals = comments[i].value; + var splits = globals.split(/\s+/); + // start with 1 to avoid 'global' + for (var j = 1; j < splits.length; j++) { + if (splits[j].length > 0) { + var colonIdx = splits[j].indexOf(':'); + if (colonIdx >= 0) { + globName = splits[j].substring(0,colonIdx).trim(); + } else { + globName = splits[j].trim(); + } + if (!env.lookupName(globName)) { + env.addOrSetVariable(globName, null, null, range); + } + } + } + break; + } + } + } + } + + /** + * Adds global variables defined in dependencies + */ + function addIndexedGlobals(env) { + // no indexer means that we should not consult indexes for extra type information + if (env.indexer) { + // get the list of summaries relevant for this file + // add it to the global scope + var summaries = env.indexer.retrieveGlobalSummaries(); + for (var fileName in summaries) { + if (summaries.hasOwnProperty(fileName)) { + env.mergeSummary(summaries[fileName], env.globalTypeName()); + } + } + } + } + + /** + * the prefix of a completion should not be included in the completion itself + * must explicitly remove it + */ + function removePrefix(prefix, string) { + return string.substring(prefix.length); + } + + /** + * Determines if the left type name is more general than the right type name. + * Generality (>) is defined as follows: + * undefined > Object > Generated empty type > all other types + * + * A generated empty type is a generated type that has only a $$proto property + * added to it. Additionally, the type specified in the $$proto property is + * either empty or is Object + * + * @param String leftTypeName + * @param String rightTypeName + * @param {{getAllTypes:function():Object}} env + * + * @return Boolean + */ + function leftTypeIsMoreGeneral(leftTypeName, rightTypeName, env) { + function isEmpty(generatedTypeName) { + if (generatedTypeName === "Object" || generatedTypeName === "undefined") { + return true; + } else if (leftTypeName.substring(0, mTypes.GEN_NAME.length) !== mTypes.GEN_NAME) { + return false; + } + + + var type = env.getAllTypes()[generatedTypeName]; + var popCount = 0; + // type should have a $$proto only and nothing else if it is empty + for (var property in type) { + if (type.hasOwnProperty(property)) { + popCount++; + if (popCount > 1) { + break; + } + } + } + if (popCount === 1) { + // we have an empty object literal, must check parent + // must traverse prototype hierarchy to make sure empty + return isEmpty(type.$$proto.typeName); + } + return false; + } + + function convertToNumber(typeName) { + if (typeName === "undefined") { + return 0; + } else if (typeName === "Object") { + return 1; + } else if (isEmpty(typeName)) { + return 2; + } else { + return 3; + } + } + + if (!rightTypeName) { + return false; + } + + var leftNum = convertToNumber(leftTypeName); + // avoid calculating the rightNum if possible + if (leftNum === 0) { + return rightTypeName !== "undefined"; + } else if (leftNum === 1) { + return rightTypeName !== "undefined" && rightTypeName !== "Object"; + } else if (leftNum === 2) { + return rightTypeName !== "undefined" && rightTypeName !== "Object" && !isEmpty(rightTypeName); + } else { + return false; + } + } + + /** + * @return boolean true iff the type contains + * prop. prop must not be coming from Object + */ + function typeContainsProperty(type, prop) { + if (! (prop in type)) { + return false; + } + if (Object.hasOwnProperty(prop)) { + // the propery may be re-defined in the current type + // check that here + return !type.hasOwnProperty(prop); + } + return true; + } + + /** + * Creates the environment object that stores type information + * Called differently depending on what job this content assistant is being called to do. + */ + function createEnvironment(options) { + var buffer = options.buffer, uid = options.uid, offset = options.offset, indexer = options.indexer, globalObjName = options.globalObjName; + if (!offset) { + offset = buffer.length+1; + } + + // must copy comments because the array is mutable + var comments = []; + if (options.comments) { + for (var i = 0; i < options.comments.length; i++) { + comments[i] = options.comments[i]; + } + } + + // prefix for generating local types + // need to add a unique id for each file so that types defined in dependencies don't clash with types + // defined locally + var namePrefix = mTypes.GEN_NAME + uid + "~"; + + return { + /** Each element is the type of the current scope, which is a key into the types array */ + _scopeStack : [globalObjName], + /** + * a map of all the types and their properties currently known + * when an indexer exists, local storage will be checked for extra type information + */ + _allTypes : new mTypes.Types(globalObjName), + /** a counter used for creating unique names for object literals and scopes */ + _typeCount : 0, + + _nameStack : [], + + /** if this is an AMD module, then the value of this property is the 'define' call expression */ + amdModule : null, + /** if this is a wrapped commonjs module, then the value of this property is the 'define' call expression */ + commonjsModule : null, + /** the indexer for thie content assist invocation. Used to track down dependencies */ + indexer: indexer, + /** the offset of content assist invocation */ + offset : offset, + /** the entire contents being completed on */ + contents : buffer, + uid : uid === 'local' ? null : uid, + + /** List of comments in the AST*/ + comments : comments, + + newName: function() { + return namePrefix + this._typeCount++; + }, + /** + * Creates a new empty scope and returns the name of the scope + * must call this.popScope() when finished with this scope + */ + newScope: function(range) { + // the prototype is always the currently top level scope + var targetType = this.scope(); + var newScopeName = this.newName(); + this._allTypes[newScopeName] = { + $$proto : new mTypes.Definition(targetType, range, this.uid) + }; + this._scopeStack.push(newScopeName); + return newScopeName; + }, + + pushScope : function(scopeName) { + this._scopeStack.push(scopeName); + }, + + pushName : function(name) { + this._nameStack.push(name); + }, + + popName : function() { + this._nameStack.pop(); + }, + + getQualifiedName : function() { + var name = this._nameStack.join('.'); + return name.length > 0 ? name + '.' : name; + }, + + /** + * Creates a new empty object scope and returns the name of this object + * must call this.popScope() when finished + */ + newObject: function(newObjectName, range) { + // object needs its own scope + this.newScope(); + // if no name passed in, create a new one + newObjectName = newObjectName? newObjectName : this.newName(); + // assume that objects have their own "this" object + // prototype of Object + this._allTypes[newObjectName] = { + $$proto : new mTypes.Definition("Object", range, this.uid) + }; + this.addVariable("this", null, newObjectName, range); + + return newObjectName; + }, + + /** + * like a call to this.newObject(), but the + * object created has not scope added to the scope stack + */ + newFleetingObject : function(name, range) { + var newObjectName = name ? name : this.newName(); + this._allTypes[newObjectName] = { + $$proto : new mTypes.Definition("Object", range, this.uid) + }; + return newObjectName; + }, + + /** removes the current scope */ + popScope: function() { + // Can't delete old scope since it may have been assigned somewhere + var oldScope = this._scopeStack.pop(); + return oldScope; + }, + + /** + * @param {ASTNode|String} target + * returns the type name for the current scope + * if a target is passed in (optional), then use the + * inferred type of the target instead (if it exists) + */ + scope : function(target) { + if (typeof target === "string") { + return target; + } + + if (target && target.extras.inferredType) { + // check for function literal + var inferredType = target.extras.inferredType; + // hmmmm... will be a problem here if there are nested ~protos + if (mTypes.isFunctionOrConstructor(inferredType) && !mTypes.isPrototype(inferredType)) { + var noArgsType = mTypes.removeParameters(inferredType); + if (this._allTypes[noArgsType]) { + return noArgsType; + } else { + return "Function"; + } + } else if (mTypes.isArrayType(inferredType)) { + // TODO FIXADE we are losing parameterization here + return "Array"; + } else { + return inferredType; + } + } else { + // grab topmost scope + return this._scopeStack[this._scopeStack.length -1]; + } + }, + + globalScope : function() { + return this._allTypes[this._scopeStack[0]]; + }, + + globalTypeName : function() { + return this._scopeStack[0]; + }, + + /** + * adds the name to the target type. + * if target is passed in then use the type corresponding to + * the target, otherwise use the current scope + * + * Will not override an existing variable if the new typeName is "Object" or "undefined" + * Will not add to a built in type + * + * @param {String} name + * @param {String} typeName + * @param {Object} target + * @param {Array.} range + * @param {Array.} docRange + */ + addVariable : function(name, target, typeName, range, docRange) { + if (this._allTypes.Object["$_$" + name]) { + // this is a built in property of object. do not redefine + return; + } + var type = this._allTypes[this.scope(target)]; + // do not allow augmenting built in types + if (!type.$$isBuiltin) { + // if new type name is not more general than old type, do not replace + if (typeContainsProperty(type, name) && leftTypeIsMoreGeneral(typeName, type[name].typeName, this)) { + // do nuthin + } else { + type[name] = new mTypes.Definition(typeName ? typeName : "Object", range, this.uid); + type[name].docRange = docRange; + return type[name]; + } + } + }, + + addOrSetGlobalVariable : function(name, typeName, range, docRange) { + if (this._allTypes.Object["$_$" + name]) { + // this is a built in property of object. do not redefine + return; + } + return this.addOrSetVariable(name, + // mock an ast node with a global type + { extras : { inferredType : this.globalTypeName() } }, typeName, range, docRange); + }, + + /** + * like add variable, but first checks the prototype hierarchy + * if exists in prototype hierarchy, then replace the type + * + * Will not override an existing variable if the new typeName is "Object" or "undefined" + */ + addOrSetVariable : function(name, target, typeName, range, docRange) { + if (name === 'prototype') { + name = '$$proto'; + } else if (this._allTypes.Object["$_$" + name]) { + // this is a built in property of object. do not redefine + return; + } + + var targetType = this.scope(target); + var current = this._allTypes[targetType], found = false; + // if no type provided, create a new type + typeName = typeName ? typeName : this.newFleetingObject(); + var defn; + while (current) { + if (typeContainsProperty(current, name)) { + defn = current[name]; + // found it, just overwrite + // do not allow overwriting of built in types + // 3 cases to avoid: + // 1. properties of builtin types cannot be set + // 2. builtin types cannot be redefined + // 3. new type name is more general than old type + if (!current.$$isBuiltin && current.hasOwnProperty(name) && + !leftTypeIsMoreGeneral(typeName, defn.typeName, this)) { + // since we are just overwriting the type we do not want to change + // the path or the range + defn.typeName = typeName; + if (docRange) { + defn.docRange = docRange; + } + } + found = true; + break; + } else if (current.$$proto) { + current = this._allTypes[current.$$proto.typeName]; + } else { + current = null; + } + } + + if (!found) { + // not found, so just add to current scope + // do not allow overwriting of built in types + var type = this._allTypes[targetType]; + if (!type.$$isBuiltin) { + defn = new mTypes.Definition(typeName, range, this.uid); + defn.docRange = docRange; + type[name] = defn; + } + } + return defn; + }, + + /** looks up the name in the hierarchy */ + lookupName : function(name, target, applyFunction, includeDefinition) { + + // translate function names on object into safe names + var swapper = function(name) { + switch (name) { + case "prototype": + return "$$proto"; + case "toString": + case "hasOwnProperty": + case "toLocaleString": + case "valueOf": + case "isProtoTypeOf": + case "propertyIsEnumerable": + return "$_$" + name; + default: + return name; + } + }; + + var innerLookup = function(name, type, allTypes) { + var res = type[name]; + + var proto = type.$$proto; + if (res) { + return includeDefinition ? res : res.typeName; + } else if (proto) { + return innerLookup(name, allTypes[proto.typeName], allTypes); + } else { + return null; + } + }; + var targetType = this._allTypes[this.scope(target)]; + + // uncomment this if we want to hide errors where there is an unknown type being placed on the scope stack +// if (!targetType) { +// targetType = this.globalScope() +// } + var res = innerLookup(swapper(name), targetType, this._allTypes); + return res; + }, + + /** removes the variable from the current type */ + removeVariable : function(name, target) { + // do not allow deleting properties of built in types + var type = this._allTypes[this.scope(target)]; + // 2 cases to avoid: + // 1. properties of builtin types cannot be deleted + // 2. builtin types cannot be deleted from global scope + if (!type.$$isBuiltin && type[name] && !(type[name] && !type.hasOwnProperty(name))) { + delete type[name]; + } + }, + + /** + * adds a file summary to this module + */ + mergeSummary : function(summary, targetTypeName) { + + // add the extra types that don't already exists + for (var type in summary.types) { + if (summary.types.hasOwnProperty(type) && !this._allTypes[type]) { + this._allTypes[type] = summary.types[type]; + } + } + + // now augment the target type with the provided properties + // but only if a composite type is exported + var targetType = this._allTypes[targetTypeName]; + if (typeof summary.provided !== 'string') { + for (var providedProperty in summary.provided) { + if (summary.provided.hasOwnProperty(providedProperty)) { + // the targetType may already have the providedProperty defined + // but should override + targetType[providedProperty] = summary.provided[providedProperty]; + } + } + } + }, + + /** + * takes the name of a constructor and converts it into a type. + * We need to ensure that ConstructorName.prototype = { ... } does the + * thing that we expect. This is why we set the $$proto property of the types + */ + createConstructor : function(constructorName, rawTypeName) { + // don't include the parameter names since we don't want them confusing things when exported + constructorName = mTypes.removeParameters(constructorName); + this.newFleetingObject(constructorName); + var flobj = this.newFleetingObject(constructorName + "~proto"); + this._allTypes[constructorName].$$proto = new mTypes.Definition(flobj, null, this.uidj); + this._allTypes[rawTypeName].$$proto = new mTypes.Definition(constructorName, null, this.uid); + }, + + findType : function(typeName) { + if (mTypes.isArrayType(typeName)) { + // TODO is there anything we need to do here? + // parameterized array + typeName = "Array"; + } + + // trim arguments if a constructor, careful to avoid a constructor prototype + if (typeName.charAt(0) === "?") { + typeName = mTypes.removeParameters(typeName); + + if (!this._allTypes[typeName]) { + // function type has not been explicitly added to list + // just return function instead + return this._allTypes.Function; + } + } + return this._allTypes[typeName]; + }, + + getAllTypes : function() { + return this._allTypes; + }, + + /** + * This function stores the target type + * so it can be used as the result of this inferencing operation + */ + storeTarget : function(targetType) { + if (!this.targetType) { + if (!targetType) { + targetType = this.scope(); + } + this.targetType = targetType; + this.targetFound = true; + } + } + }; + } + + function createProposalDescription(propName, propType, env) { + return propName + " : " + mTypes.createReadableType(propType, env); + } + + function createInferredProposals(targetTypeName, env, completionKind, prefix, replaceStart, proposals, relevance) { + var prop, propName, propType, res, type = env.findType(targetTypeName), proto = type.$$proto; + if (!relevance) { + relevance = 100; + } + // start at the top of the prototype hierarchy so that duplicates can be removed + if (proto) { + createInferredProposals(proto.typeName, env, completionKind, prefix, replaceStart, proposals, relevance - 10); + } + + // add a separator proposal + proposals['---dummy' + relevance] = { + proposal: '', + description: '---------------------------------', + relevance: relevance -1, + style: 'hr', + unselectable: true + }; + + // need to look at prototype for global and window objects + // so need to traverse one level up prototype hierarchy if + // the next level is not Object + var realProto = Object.getPrototypeOf(type); + var protoIsObject = !Object.getPrototypeOf(realProto); + for (prop in type) { + if (type.hasOwnProperty(prop) || (!protoIsObject && realProto.hasOwnProperty(prop))) { + if (prop.charAt(0) === "$" && prop.charAt(1) === "$") { + // special property + continue; + } + if (!proto && prop.indexOf("$_$") === 0) { + // no prototype that means we must decode the property name + propName = prop.substring(3); + } else { + propName = prop; + } + if (propName === "this" && completionKind === "member") { + // don't show "this" proposals for non-top-level locations + // (eg- this.this is wrong) + continue; + } + if (!type[prop].typeName) { + // minified files sometimes have invalid property names (eg- numbers). Ignore them) + continue; + } + if (proposalUtils.looselyMatches(prefix, propName)) { + propType = type[prop].typeName; + var first = propType.charAt(0); + if (first === "?" || first === "*") { + // we have a function + res = calculateFunctionProposal(propName, + propType, replaceStart - 1); + var funcDesc = res.completion + " : " + mTypes.createReadableType(propType, env); + proposals["$"+propName] = { + proposal: removePrefix(prefix, res.completion), + description: funcDesc, + positions: res.positions, + escapePosition: replaceStart + res.completion.length, + // prioritize methods over fields + relevance: relevance + 5, + style: 'emphasis' + }; + } else { + proposals["$"+propName] = { + proposal: removePrefix(prefix, propName), + relevance: relevance, + description: createProposalDescription(propName, propType, env), + style: 'emphasis' + }; + } + } + } + } + } + + function createNoninferredProposals(environment, prefix, replaceStart, proposals) { + var proposalAdded = false; + // a property to return is one that is + // 1. defined on the type object + // 2. prefixed by the prefix + // 3. doesn't already exist + // 4. is not an internal property + function isInterestingProperty(type, prop) { + return type.hasOwnProperty(prop) && prop.indexOf(prefix) === 0 && !proposals['$' + prop] && prop !== '$$proto'&& prop !== '$$isBuiltin'; + } + function forType(type) { + for (var prop in type) { + if (isInterestingProperty(type, prop)) { + var propType = type[prop].typeName; + var first = propType.charAt(0); + if (first === "?" || first === "*") { + var res = calculateFunctionProposal(prop, propType, replaceStart - 1); + proposals[prop] = { + proposal: removePrefix(prefix, res.completion), + description: createProposalDescription(prop, propType, environment), + positions: res.positions, + escapePosition: replaceStart + res.completion.length, + // prioritize methods over fields + relevance: -99, + style: 'noemphasis' + }; + proposalAdded = true; + } else { + proposals[prop] = { + proposal: removePrefix(prefix, prop), + description: createProposalDescription(prop, propType, environment), + relevance: -100, + style: 'noemphasis' + }; + proposalAdded = true; + } + } + } + } + var allTypes = environment.getAllTypes(); + for (var typeName in allTypes) { + // need to traverse into the prototype + if (allTypes[typeName].$$proto) { + forType(allTypes[typeName]); + } + } + + if (proposalAdded) { + proposals['---dummy'] = { + proposal: '', + description: 'Non-inferred proposals', + relevance: -98, + style: 'noemphasis', + unselectable: true + }; + } + } + + function findUnreachable(currentTypeName, allTypes, alreadySeen) { + if (currentTypeName.charAt(0) === '*') { + // constructors are not stored with their arguments so need to remove them in order to find them + currentTypeName = mTypes.removeParameters(currentTypeName); + } + var currentType = allTypes[currentTypeName]; + if (currentType) { + for(var prop in currentType) { + if (currentType.hasOwnProperty(prop) && prop !== '$$isBuiltin' ) { + var propType = currentType[prop].typeName; + while (mTypes.isFunctionOrConstructor(propType) || mTypes.isArrayType(propType)) { + if (!alreadySeen[propType]) { + alreadySeen[propType] = true; + findUnreachable(propType, allTypes, alreadySeen); + } + if (mTypes.isFunctionOrConstructor(propType)) { + propType = mTypes.extractReturnType(propType); + } else if (mTypes.isArrayType(propType)) { + propType = mTypes.extractArrayParameterType(propType); + } + } + if (!alreadySeen[propType]) { + alreadySeen[propType] = true; + findUnreachable(propType, allTypes, alreadySeen); + } + } + } + } + } + + /** + * filters types from the environment that should not be exported + */ + function filterTypes(environment, kind, moduleTypeName) { + var allTypes = environment.getAllTypes(); + if (kind === "global") { + // for global dependencies must keep the global scope, but remove all builtin global variables + allTypes.clearDefaultGlobal(); + } else { + delete allTypes.Global; + } + + // recursively walk the type tree to find unreachable types and delete them, too + var reachable = { }; + // if we have a function, then the function return type and its prototype are reachable + // also do same if parameterized array type + // in the module, so add them + if (mTypes.isFunctionOrConstructor(moduleTypeName) || mTypes.isArrayType(moduleTypeName)) { + var retType = moduleTypeName; + while (mTypes.isFunctionOrConstructor(retType) || mTypes.isArrayType(retType)) { + if (mTypes.isFunctionOrConstructor(retType)) { + retType = mTypes.removeParameters(retType); + reachable[retType] = true; + var constrType; + if (retType.charAt(0) === "?") { + // this is a function, not a constructor, but we also + // need to expose the constructor if one exists. + constrType = "*" + retType.substring(1); + reachable[constrType] = true; + } else { + constrType = retType; + } + // don't strictly need this if the protoype of the object has been changed, but OK to keep + reachable[constrType + "~proto"] = true; + retType = mTypes.extractReturnType(retType); + } else if (mTypes.isArrayType(retType)) { + retType = mTypes.extractArrayParameterType(retType); + if (retType) { + reachable[retType] = true; + } else { + retType = "Object"; + } + } + } + reachable[retType] = true; + } + + findUnreachable(moduleTypeName, allTypes, reachable); + for (var prop in allTypes) { + if (allTypes.hasOwnProperty(prop) && !reachable[prop]) { + delete allTypes[prop]; + } + } + } + + var browserRegExp = /browser\s*:\s*true/; + var nodeRegExp = /node\s*:\s*true/; + function findGlobalObject(comments, lintOptions) { + + for (var i = 0; i < comments.length; i++) { + var comment = comments[i]; + if (comment.type === "Block" && (comment.value.substring(0, "jslint".length) === "jslint" || + comment.value.substring(0,"jshint".length) === "jshint")) { + // the lint options section. now look for the browser or node + if (comment.value.match(browserRegExp)) { + return "Window"; + } else if (comment.value.match(nodeRegExp)) { + return "Module"; + } else { + return "Global"; + } + } + } + if (lintOptions && lintOptions.options) { + if (lintOptions.options.browser === true) { + return "Window"; + } else if (lintOptions.options.node === true) { + return "Module"; + } + } + return "Global"; + } + + function filterAndSortProposals(proposalsObj) { + // convert from object to array + var proposals = []; + for (var prop in proposalsObj) { + if (proposalsObj.hasOwnProperty(prop)) { + proposals.push(proposalsObj[prop]); + } + } + proposals.sort(function(l,r) { + // sort by relevance and then by name + if (l.relevance > r.relevance) { + return -1; + } else if (r.relevance > l.relevance) { + return 1; + } + + var ldesc = l.description.toLowerCase(); + var rdesc = r.description.toLowerCase(); + if (ldesc < rdesc) { + return -1; + } else if (rdesc < ldesc) { + return 1; + } + return 0; + }); + + // filter trailing and leading dummies, as well as double dummies + var toRemove = []; + + // now remove any leading or trailing dummy proposals as well as double dummies + var i = proposals.length -1; + while (i >= 0 && proposals[i].description.indexOf('---') === 0) { + toRemove[i] = true; + i--; + } + i = 0; + while (i < proposals.length && proposals[i].description.indexOf('---') === 0) { + toRemove[i] = true; + i++; + } + i += 1; + while (i < proposals.length) { + if (proposals[i].description.indexOf('---') === 0 && proposals[i-1].description.indexOf('---') === 0) { + toRemove[i] = true; + } + i++; + } + + var newProposals = []; + for (i = 0; i < proposals.length; i++) { + if (!toRemove[i]) { + newProposals.push(proposals[i]); + } + } + + return newProposals; + } + + + /** + * indexer is optional. When there is no indexer passed in + * the indexes will not be consulted for extra references + * @param {{hasDependency,performIndex,retrieveSummary,retrieveGlobalSummaries}} indexer + * @param {{global:[],options:{browser:Boolean}}=} lintOptions optional set of extra lint options that can be overridden in the source (jslint or jshint) + */ + function EsprimaJavaScriptContentAssistProvider(indexer, lintOptions) { + this.indexer = indexer; + this.lintOptions = lintOptions; + } + + /** + * Main entry point to provider + */ + EsprimaJavaScriptContentAssistProvider.prototype = { + + _doVisit : function(root, environment) { + // first augment the global scope with things we know + addLintGlobals(environment, this.lintOptions); + addIndexedGlobals(environment); + + // now we can remove all non-doc comments from the comments list + var newComments = []; + for (var i = 0; i < environment.comments.length; i++) { + if (environment.comments[i].value.charAt(0) === '*') { + newComments.push(environment.comments[i]); + } + } + environment.comments = newComments; + + try { + mVisitor.visit(root, environment, inferencer, inferencerPostOp); + } catch (done) { + if (typeof done !== "string") { + // a real error + throw done; + } + return done; + } + throw new Error("The visit function should always end with a throwable"); + }, + + /** + * implements the Orion content assist API + */ + computeProposals: function(buffer, offset, context) { + if (context.selection && context.selection.start !== context.selection.end) { + // only propose if an empty selection. + return null; + } + + try { + var root = mVisitor.parse(buffer); + if (!root) { + // assume a bad parse + return null; + } + // note that if selection has length > 0, then just ignore everything past the start + var completionKind = shouldVisit(root, offset, context.prefix, buffer); + if (completionKind) { + var environment = createEnvironment({ buffer: buffer, uid : "local", offset : offset, indexer : this.indexer, globalObjName : findGlobalObject(root.comments, this.lintOptions), comments : root.comments }); + // must defer inferring the containing function block until the end + environment.defer = completionKind.toDefer; + if (environment.defer) { + // remove these comments from consideration until we are inferring the deferred + environment.deferredComments = extractDocComments(environment.comments, environment.defer.range); + } + var target = this._doVisit(root, environment); + var proposalsObj = { }; + createInferredProposals(target, environment, completionKind.kind, context.prefix, offset - context.prefix.length, proposalsObj); + if (false && !context.inferredOnly) { + // include the entire universe as potential proposals + createNoninferredProposals(environment, context.prefix, offset - context.prefix.length, proposalsObj); + } + return filterAndSortProposals(proposalsObj); + } else { + // invalid completion location + return []; + } + } catch (e) { + if (typeof scriptedLogger !== "undefined") { + scriptedLogger.error(e.message, "CONTENT_ASSIST"); + scriptedLogger.error(e.stack, "CONTENT_ASSIST"); + } + throw (e); + } + }, + + + _internalFindDefinition : function(buffer, offset, findName) { + var toLookFor; + var root = mVisitor.parse(buffer); + if (!root) { + // assume a bad parse + return null; + } + var funcList = []; + var environment = createEnvironment({ buffer: buffer, uid : "local", offset : offset, indexer : this.indexer, globalObjName : findGlobalObject(root.comments, this.lintOptions), comments : root.comments }); + var findIdentifier = function(node) { + if ((node.type === "Identifier" || node.type === "ThisExpression") && inRange(offset, node.range, true)) { + toLookFor = node; + // cut visit short + throw "done"; + } + // FIXADE esprima bug...some call expressions have incorrect slocs. + // This is fixed in trunk of esprima. + // after next upgrade of esprima if the following has correct slocs, then + // can remove the second part of the && + // mUsers.getUser().name + if (node.range[0] > offset && + (node.type === "ExpressionStatement" || + node.type === "ReturnStatement" || + node.type === "ifStatement" || + node.type === "WhileStatement" || + node.type === "Program")) { + // not at a valid hover location + throw "no hover"; + } + + // the last function pushed on is the one that we need to defer + if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression") { + funcList.push(node); + } + return true; + }; + + try { + mVisitor.visit(root, {}, findIdentifier, function(node) { + if (node === funcList[funcList.length-1]) { + funcList.pop(); + } + }); + } catch (e) { + if (e === "no hover") { + // not at a valid hover location + return null; + } else if (e === "done") { + // valid hover...continue + } else { + // a real exception + throw e; + } + } + if (!toLookFor) { + // no hover target found + return null; + } + // must defer inferring the containing function block until the end + environment.defer = funcList.pop(); + if (environment.defer && toLookFor === environment.defer.id) { + // don't defer if target is name of function + delete environment.defer; + } + + if (environment.defer) { + // remove these comments from consideration until we are inferring the deferred + environment.deferredComments = extractDocComments(environment.comments, environment.defer.range); + } + + var target = this._doVisit(root, environment); + var lookupName = toLookFor.type === "Identifier" ? toLookFor.name : 'this'; + var maybeType = environment.lookupName(lookupName, toLookFor.extras.target || target, false, true); + if (maybeType) { + var hover = mTypes.styleAsProperty(lookupName, findName) + " : " + mTypes.createReadableType(maybeType.typeName, environment, true, 0, findName); + maybeType.hoverText = hover; + return maybeType; + } else { + return null; + } + + }, + /** + * Computes the hover information for the provided offset + */ + computeHover: function(buffer, offset) { + return this._internalFindDefinition(buffer, offset, true); + }, + + findDefinition : function(buffer, offset) { + return this._internalFindDefinition(buffer, offset, false); + }, + + /** + * Computes a summary of the file that is suitable to be stored locally and used as a dependency + * in another file + * @param {String} buffer + * @param {String} fileName + */ + computeSummary: function(buffer, fileName) { + var root = mVisitor.parse(buffer); + if (!root) { + // assume a bad parse + return null; + } + var environment = createEnvironment({ buffer: buffer, uid : fileName, globalObjName : findGlobalObject(root.comments, this.lintOptions), comments : root.comments, indexer : this.indexer }); + try { + this._doVisit(root, environment); + } catch (e) { + if (typeof scriptedLogger !== "undefined") { + scriptedLogger.error("Problem with: " + fileName, "CONTENT_ASSIST"); + scriptedLogger.error(e.message, "CONTENT_ASSIST"); + scriptedLogger.error(e.stack, "CONTENT_ASSIST"); + } + throw (e); + } + var provided; + var kind; + var modType; + if (environment.amdModule) { + // provide the exports of the AMD module + // the exports is the return value of the final argument + var args = environment.amdModule["arguments"]; + if (args && args.length > 0) { + modType = mTypes.extractReturnType(args[args.length-1].extras.inferredType); + } else { + modType = "Object"; + } + kind = "AMD"; + } else if (environment.commonjsModule) { + // a wrapped commonjs module + // we have already checked the correctness of this function + var exportsParam = environment.commonjsModule["arguments"][0].params[1]; + modType = exportsParam.extras.inferredType; + provided = provided = environment.findType(modType); + + } else { + // assume a non-module + provided = environment.globalScope(); + + if (provided.exports) { + // actually, commonjs + kind = "commonjs"; + modType = provided.exports.typeName; + } else { + kind = "global"; + modType = environment.globalTypeName(); + } + } + + // simplify the exported type + if (mTypes.isFunctionOrConstructor(modType) || environment.findType(modType).$$isBuiltin) { + // this module provides a built in type or a function + provided = modType; + } else { + // this module provides a composite type + provided = environment.findType(modType); + } + + + // now filter the builtins since they are always available + filterTypes(environment, kind, modType); + + var allTypes = environment.getAllTypes(); + + return { + provided : provided, + types : allTypes, + kind : kind + }; + } + }; + return { + EsprimaJavaScriptContentAssistProvider : EsprimaJavaScriptContentAssistProvider + }; +}); diff --git a/scripts/lib/esprima-master/assets/orion/contentassist/esprimaVisitor.js b/scripts/lib/esprima-master/assets/orion/contentassist/esprimaVisitor.js new file mode 100755 index 0000000..9f5422a --- /dev/null +++ b/scripts/lib/esprima-master/assets/orion/contentassist/esprimaVisitor.js @@ -0,0 +1,119 @@ +/******************************************************************************* + * @license + * Copyright (c) 2012 VMware, Inc. All Rights Reserved. + * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE + * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE + * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT. + * You can obtain a current copy of the Eclipse Public License from + * http://www.opensource.org/licenses/eclipse-1.0.php + * + * Contributors: + * Andrew Eisenberg (VMware) - initial API and implementation + ******************************************************************************/ + +/*global define esprima */ +define("plugins/esprima/esprimaVisitor", function(scriptedLogger) { + + + + return { + + /** + * parses the contents with options that are appropriate for inferencing + */ + parse : function(contents, extraOptions) { + if (!extraOptions) { + extraOptions = {}; + } + if (!extraOptions.range) { + extraOptions.range = true; + } + if (!extraOptions.tolerant) { + extraOptions.tolerant = true; + } + if (!extraOptions.comment) { + extraOptions.comment = true; + } + try { + var parsedProgram = esprima.parse(contents, extraOptions); + return parsedProgram; + } catch (e) { + if (typeof scriptedLogger !== "undefined") { + scriptedLogger.warn("Problem parsing file", "CONTENT_ASSIST"); + scriptedLogger.warn(e.message, "CONTENT_ASSIST"); + scriptedLogger.warn(e.stack, "CONTENT_ASSIST"); + } + return null; + } + }, + + /** + * Generic AST visitor. Visits all children in source order, if they have a range property. + * + * @param node The AST node to visit + * @param {rhsVisit:Boolean,...} context any extra data required to pass between operations. Set rhsVisit to true if the rhs of + * assignments and variable declarators should be visited before the lhs + * @param operation function(node, context, [isInitialOp]) an operation on the AST node and the data. Return falsy if + * the visit should no longer continue. Return truthy to continue. + * @param [postoperation] (optional) function(node, context, [isInitialOp]) an operation that is exectuted after visiting the current node's children. + * will only be invoked if operation returns true for the current node + */ + visit: function(node, context, operation, postoperation) { + var i, key, child, children; + + if (operation(node, context, true)) { + // gather children to visit + children = []; + for (key in node) { + if (key !== "range" && key !== "errors" && key !== "target" && key !== "extras" && key !== "comments") { + child = node[key]; + if (child instanceof Array) { + for (i = 0; i < child.length; i++) { + if (child[i] && child[i].hasOwnProperty("type")) { + children.push(child[i]); + } else if (key === "properties") { + // might be key-value pair of an object expression + // in old versions of the parser, the 'properties' property did not have a 'type' or a 'range' + // so we must explicitly visit the children here. + // in new versions of the parser, this is fixed, and this branch will never be taken. + if (child[i].hasOwnProperty("key") && child[i].hasOwnProperty("value")) { + children.push(child[i].key); + children.push(child[i].value); + } + } + } + } else { + if (child && child.hasOwnProperty("type")) { + children.push(child); + } + } + } + } + + if (children.length > 0) { + // sort children by source location + // children with no source location are visited first + children.sort(function(left, right) { + if (left.range && right.range) { + return left.range[0] - right.range[0]; + } else if (left.range) { + return 1; + } else if (right.range) { + return -1; + } else { + return 0; + } + }); + + // visit children in order + for (i = 0; i < children.length; i++) { + this.visit(children[i], context, operation, postoperation); + } + } + if (postoperation) { + postoperation(node, context, false); + } + } + } + }; +}); diff --git a/scripts/lib/esprima-master/assets/orion/contentassist/proposalUtils.js b/scripts/lib/esprima-master/assets/orion/contentassist/proposalUtils.js new file mode 100755 index 0000000..6c6fb5f --- /dev/null +++ b/scripts/lib/esprima-master/assets/orion/contentassist/proposalUtils.js @@ -0,0 +1,104 @@ +/******************************************************************************* + * @license + * Copyright (c) 2012 VMware, Inc. All Rights Reserved. + * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE + * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE + * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT. + * You can obtain a current copy of the Eclipse Public License from + * http://www.opensource.org/licenses/eclipse-1.0.php + * + * Contributors: + * Andy Clement (VMware) - initial API and implementation + * Andrew Eisenberg (VMware) - implemented visitor pattern + ******************************************************************************/ + +/*global define */ +define("plugins/esprima/proposalUtils", { + /** + * Match ignoring case and checking camel case. + * @param prefix + * @param target + * @return + */ + looselyMatches: function(prefix, target) { + if (target === null || prefix === null) { + return false; + } + + // Zero length string matches everything. + if (prefix.length === 0) { + return true; + } + + // Exclude a bunch right away + if (prefix.charAt(0).toLowerCase() !== target.charAt(0).toLowerCase()) { + return false; + } + + if (this.startsWith(target, prefix)) { + return true; + } + + var lowerCase = target.toLowerCase(); + if (this.startsWith(lowerCase, prefix)) { + return true; + } + + // Test for camel characters in the prefix. + if (prefix === prefix.toLowerCase()) { + return false; + } + + var prefixParts = this.toCamelCaseParts(prefix); + var targetParts = this.toCamelCaseParts(target); + + if (prefixParts.length > targetParts.length) { + return false; + } + + for (var i = 0; i < prefixParts.length; ++i) { + if (!this.startsWith(targetParts[i], prefixParts[i])) { + return false; + } + } + + return true; + }, + + /** + * Convert an input string into parts delimited by upper case characters. Used for camel case matches. + * e.g. GroClaL = ['Gro','Cla','L'] to match say 'GroovyClassLoader'. + * e.g. mA = ['m','A'] + * @param String str + * @return Array. + */ + toCamelCaseParts: function(str) { + var parts = []; + for (var i = str.length - 1; i >= 0; --i) { + if (this.isUpperCase(str.charAt(i))) { + parts.push(str.substring(i)); + str = str.substring(0, i); + } + } + if (str.length !== 0) { + parts.push(str); + } + return parts.reverse(); + }, + + startsWith : function(str, start) { + return str.substr(0, start.length) === start; + }, + + isUpperCase : function(char) { + return char >= 'A' && char <= 'Z'; + }, + + repeatChar : function(char, times) { + var str = ""; + for (var i = 0; i < times; i++) { + str += char; + } + return str; + } +}); diff --git a/scripts/lib/esprima-master/assets/orion/contentassist/types.js b/scripts/lib/esprima-master/assets/orion/contentassist/types.js new file mode 100755 index 0000000..139f4ee --- /dev/null +++ b/scripts/lib/esprima-master/assets/orion/contentassist/types.js @@ -0,0 +1,1930 @@ +/******************************************************************************* + * @license + * Copyright (c) 2012 VMware, Inc. All Rights Reserved. + * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE + * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE + * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT. + * You can obtain a current copy of the Eclipse Public License from + * http://www.opensource.org/licenses/eclipse-1.0.php + * + * Contributors: + * Andrew Eisenberg (VMware) - initial API and implementation + ******************************************************************************/ + +/* +This module defines the built in types for the scripted JS inferencer. +It also contains functions for manipulating internal type signatures. + +Here is the BNF for internal type signature: + + ::= | | | | + + ::= js_identifier // simple types are just js identifiers + + ::= "Array.[" "]" // a bit verbose for array types, but following syntax of closure compiler + + ::= "~proto" // specifies that this type is a prototype of the base type + + ::= "?" ":" ( ",")* // function types have one or more paramteters + + ::= "*" ":" ( ",")* // same as function type, but with different start + + ::= js_identifier ("/" )? // a parameter type consists of a name and an optional type, separated by a / +*/ + + +/*global define doctrine */ +define("plugins/esprima/types", ["plugins/esprima/proposalUtils"], function(proposalUtils, scriptedLogger) { + + /** + * The Definition class refers to the declaration of an identifier. + * The start and end are locations in the source code. + * Path is a URL corresponding to the document where the definition occurs. + * If range is undefined, then the definition refers to the entire document + * Range is a two element array with the start and end values + * (Exactly the same range field as is used in Esprima) + * If the document is undefined, then the definition is in the current document. + * + * @param String typeName + * @param {Array.} range + * @param String path + */ + var Definition = function(typeName, range, path) { + this.typeName = typeName; + this.range = range; + this.path = path; + }; + + // From ecma script manual 262 section 15 + // the global object when not in browser or node + var Global = function() {}; + Global.prototype = { + $$proto : new Definition("Object"), + + decodeURI : new Definition("?String:uri"), + encodeURI : new Definition("?String:uri"), + 'eval' : new Definition("?Object:toEval"), + parseInt : new Definition("?Number:str,[radix]"), + parseFloat : new Definition("?Number:str,[radix]"), + "this": new Definition("Global"), + Math: new Definition("Math"), + JSON: new Definition("JSON"), + Object: new Definition("*Object:[val]"), + Function: new Definition("*Function:"), + Array: new Definition("*Array:[val]"), + Boolean: new Definition("*Boolean:[val]"), + Number: new Definition("*Number:[val]"), + Date: new Definition("*Date:[val]"), + RegExp: new Definition("*RegExp:[val]"), + Error: new Definition("*Error:[err]"), + 'undefined' : new Definition("undefined"), + isNaN : new Definition("?Boolean:num"), + isFinite : new Definition("?Boolean:num"), + "NaN" : new Definition("Number"), + "Infinity" : new Definition("Number"), + decodeURIComponent : new Definition("?String:encodedURIString"), + encodeURIComponent : new Definition("?String:decodedURIString") + + // not included since not meant to be referenced directly + // EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError + }; + + // Node module + var Module = function() {}; + Module.prototype = { + + // From Window + decodeURI : new Definition("?String:uri"), + encodeURI : new Definition("?String:uri"), + 'eval' : new Definition("?Object:toEval"), + parseInt : new Definition("?Number:str,[radix]"), + parseFloat : new Definition("?Number:str,[radix]"), + "this": new Definition("Module"), + Math: new Definition("Math"), + JSON: new Definition("JSON"), + Object: new Definition("*Object:[val]"), + Function: new Definition("*Function:"), + Array: new Definition("*Array:[val]"), + Boolean: new Definition("*Boolean:[val]"), + Number: new Definition("*Number:[val]"), + Date: new Definition("*Date:[val]"), + RegExp: new Definition("*RegExp:[val]"), + Error: new Definition("*Error:[err]"), + 'undefined' : new Definition("undefined"), + isNaN : new Definition("?Boolean:num"), + isFinite : new Definition("?Boolean:num"), + "NaN" : new Definition("Number"), + "Infinity" : new Definition("Number"), + decodeURIComponent : new Definition("?String:encodedURIString"), + encodeURIComponent : new Definition("?String:decodedURIString"), + + + Buffer: new Definition("Object"), + console: new Definition("Object"), + module: new Definition("Module"), + process: new Definition("Process"), + + require: new Definition("?Object:module"), +// exports: new Definition("Object"), + clearInterval: new Definition("?undefined:t"), + clearTimeout: new Definition("?undefined:t"), + setInterval: new Definition("?Number:callback,ms"), + setTimeout : new Definition("?Number:callback,ms"), + global: new Definition("Module"), + querystring: new Definition("String"), + __filename: new Definition("String"), + __dirname: new Definition("String") + }; + + var Window = function() {}; + Window.prototype = { + // copied from Global + $$proto : new Definition("Object"), + + decodeURI : new Definition("?String:uri"), + encodeURI : new Definition("?String:uri"), + 'eval' : new Definition("?Object:toEval"), + parseInt : new Definition("?Number:str,[radix]"), + parseFloat : new Definition("?Number:str,[radix]"), + "this": new Definition("Window"), + Math: new Definition("Math"), + JSON: new Definition("JSON"), + Object: new Definition("*Object:[val]"), + Function: new Definition("*Function:"), + Array: new Definition("*Array:[val]"), + Boolean: new Definition("*Boolean:[val]"), + Number: new Definition("*Number:[val]"), + Date: new Definition("*Date:[val]"), + RegExp: new Definition("*RegExp:[val]"), + Error: new Definition("*Error:[err]"), + 'undefined' : new Definition("undefined"), + isNaN : new Definition("?Boolean:num"), + isFinite : new Definition("?Boolean:num"), + "NaN" : new Definition("Number"), + "Infinity" : new Definition("Number"), + decodeURIComponent : new Definition("?String:encodedURIString"), + encodeURIComponent : new Definition("?String:decodedURIString"), + + // see https://developer.mozilla.org/en/DOM/window + // Properties + applicationCache : new Definition("DOMApplicationCache"), + closed : new Definition("Boolean"), + console : new Definition("Console"), + defaultStatus : new Definition("String"), + document : new Definition("Document"), + frameElement : new Definition("Element"), + frames : new Definition("Array"), + history : new Definition("History"), + innerHeight : new Definition("Number"), + innerWidth : new Definition("Number"), + length : new Definition("Number"), + location : new Definition("Location"), + locationbar : new Definition("BarInfo"), + localStorage : new Definition("Storage"), + menubar : new Definition("BarInfo"), + name : new Definition("String"), + navigator : new Definition("Navigator"), + opener : new Definition("Window"), + outerHeight : new Definition("Number"), + outerWidth : new Definition("Number"), + pageXOffset : new Definition("Number"), + pageYOffset : new Definition("Number"), + parent : new Definition("Window"), + performance : new Definition("Performance"), + personalbar : new Definition("BarInfo"), + screen : new Definition("Screen"), + screenX : new Definition("Number"), + screenY : new Definition("Number"), + scrollbars : new Definition("BarInfo"), + scrollMaxX : new Definition("Number"), + scrollMaxY : new Definition("Number"), + scrollX : new Definition("Number"), + scrollY : new Definition("Number"), + self : new Definition("Window"), + sessionStorage : new Definition("Storage"), + sidebar : new Definition("BarInfo"), + status : new Definition("String"), + statusbar : new Definition("BarInfo"), + toolbar : new Definition("BarInfo"), + top : new Definition("Window"), + window : new Definition("Window"), + + // Methods + // commented methods are mozilla-specific + addEventListener : new Definition("?undefined:"), + alert : new Definition("?undefined:String"), + atob : new Definition("?String:val"), + back : new Definition("?undefined:"), + blur : new Definition("?undefined:"), + btoa : new Definition("?String:val"), + clearInterval : new Definition("?undefined:interval"), + clearTimeout : new Definition("?undefined:timeout"), + close : new Definition("?undefined:"), + confirm : new Definition("?Boolean:msg"), + //disableExternalCapture : new Definition("???"), + dispatchEvent : new Definition("?undefined:domnode"), + dump : new Definition("?undefined:message"), + //enableExternalCapture : new Definition("???"), + escape : new Definition("?String:str"), + find : new Definition("?Boolean:text"), + focus : new Definition("?undefined:"), + forward : new Definition("?undefined:"), + getAttention : new Definition("?undefined:"), + getComputedStyle : new Definition("?CSSStyleDeclaration:dombode"), + getSelection : new Definition("?Selection:"), + home : new Definition("?undefined:"), + matchMedia : new Definition("?MediaQueryList:query"), + //maximize : new Definition("???"), + //minimize : new Definition("???"), + moveBy : new Definition("?undefined:deltaX,deltaY"), + moveTo : new Definition("?undefined:x,y"), + open : new Definition("?Window:strUrl,strWindowName,[strWindowFeatures]"), + openDialog : new Definition("?Window:strUrl,strWindowName,strWindowFeatures,[args]"), + postMessage : new Definition("?undefined:message,targetOrigin"), + print : new Definition("?undefined:"), + prompt : new Definition("?String:message"), + removeEventListener : new Definition("?undefined:type,listener,[useCapture]"), + resizeBy : new Definition("?undefined:deltaX,deltaY"), + resizeTo : new Definition("?undefined:x,y"), + scroll : new Definition("?undefined:x,y"), + scrollBy : new Definition("?undefined:deltaX,deltaY"), + scrollByLines : new Definition("?undefined:lines"), + scrollByPages : new Definition("?undefined:pages"), + scrollTo : new Definition("?undefined:x,y"), + setCursor : new Definition("?undefined:cursor"), + setInterval : new Definition("?Number:func,interval"), + //setResizable : new Definition("???"), + setTimeout : new Definition("?Number:func,timeout"), + sizeToContent : new Definition("?undefined:"), + stop : new Definition("?undefined:"), + unescape : new Definition("?String:str"), + updateCommands : new Definition("?undefined:cmdName"), + + // Events + onabort : new Definition("?undefined:event"), + onbeforeunload : new Definition("?undefined:event"), + onblur : new Definition("?undefined:event"), + onchange : new Definition("?undefined:event"), + onclick : new Definition("?undefined:event"), + onclose : new Definition("?undefined:event"), + oncontextmenu : new Definition("?undefined:event"), + ondevicemotion : new Definition("?undefined:event"), + ondeviceorientation : new Definition("?undefined:event"), + ondragdrop : new Definition("?undefined:event"), + onerror : new Definition("?undefined:event"), + onfocus : new Definition("?undefined:event"), + onhashchange : new Definition("?undefined:event"), + onkeydown : new Definition("?undefined:event"), + onkeypress : new Definition("?undefined:event"), + onkeyup : new Definition("?undefined:event"), + onload : new Definition("?undefined:event"), + onmousedown : new Definition("?undefined:event"), + onmousemove : new Definition("?undefined:event"), + onmouseout : new Definition("?undefined:event"), + onmouseover : new Definition("?undefined:event"), + onmouseup : new Definition("?undefined:event"), + onpaint : new Definition("?undefined:event"), + onpopstate : new Definition("?undefined:event"), + onreset : new Definition("?undefined:event"), + onresize : new Definition("?undefined:event"), + onscroll : new Definition("?undefined:event"), + onselect : new Definition("?undefined:event"), + onsubmit : new Definition("?undefined:event"), + onunload : new Definition("?undefined:event"), + onpageshow : new Definition("?undefined:event"), + onpagehide : new Definition("?undefined:event"), + + // Constructors + Image : new Definition("*HTMLImageElement:[width],[height]"), + Option : new Definition("*HTMLOptionElement:[text].[value],[defaultSelected],[selected]"), + Worker : new Definition("*Worker:url"), + XMLHttpRequest : new Definition("*XMLHttpRequest:"), + WebSocket : new Definition("*WebSocket:url,protocols"), + Event : new Definition("*Event:type"), + Node : new Definition("*Node:") + }; + + var initialGlobalProperties = []; + for (var prop in Global) { + if (Global.hasOwnProperty(prop)) { + initialGlobalProperties.push(prop); + } + } + + for (prop in Window) { + if (Window.hasOwnProperty(prop)) { + initialGlobalProperties.push(prop); + } + } + + /** + * A prototype that contains the common built-in types + */ + var Types = function(globalObjName) { + + // this object can be touched by clients + // and so must not be in the prototype + // the global 'this' + if (globalObjName === 'Window') { + this.Window = new Window(); + } else if (globalObjName === 'Module') { + this.Module = new Module(); + } else { + this.Global = new Global(); + } + + // TODO FIXADE should be declared on prototype + this.clearDefaultGlobal = function() { + for (var i = 0; i < initialGlobalProperties.length; i++) { + if (this.Global[initialGlobalProperties[i]]) { + delete this.Global[initialGlobalProperties[i]]; + } + } + }; + + }; + + + /** + * Populate the Types object with built-in types. These are not meant to be changed through the inferencing process + * This uses the built in types as defined in the ECMA script reference manual 262. Available at + * http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf section 15. + */ + Types.prototype = { + + /** + * See 15.2.4 Properties of the Object Prototype Object + */ + Object : { + $$isBuiltin: true, + // Can't use the real propoerty name here because would override the real methods of that name + $_$prototype : new Definition("Object"), + $_$toString: new Definition("?String:"), + $_$toLocaleString : new Definition("?String:"), + $_$valueOf: new Definition("?Object:"), + $_$hasOwnProperty: new Definition("?Boolean:property"), + $_$isPrototypeOf: new Definition("?Boolean:object"), + $_$propertyIsEnumerable: new Definition("?Boolean:property") + }, + + /** + * See 15.3.4 Properties of the Function Prototype Object + */ + Function : { + $$isBuiltin: true, + apply : new Definition("?Object:func,[argArray]"), + "arguments" : new Definition("Arguments"), + bind : new Definition("?Object:func,[args...]"), + call : new Definition("?Object:func,[args...]"), + caller : new Definition("Function"), + length : new Definition("Number"), + name : new Definition("String"), + $$proto : new Definition("Object") + }, + + /** + * See 15.4.4 Properties of the Array Prototype Object + */ + Array : { + $$isBuiltin: true, + + concat : new Definition("?Array:first,[rest...]"), + join : new Definition("?String:separator"), + length : new Definition("Number"), + pop : new Definition("?Object:"), + push : new Definition("?Object:[vals...]"), + reverse : new Definition("?Array:"), + shift : new Definition("?Object:"), + slice : new Definition("?Array:start,deleteCount,[items...]"), + splice : new Definition("?Array:start,end"), + sort : new Definition("?Array:[sorter]"), + unshift : new Definition("?Number:[items...]"), + indexOf : new Definition("?Number:searchElement,[fromIndex]"), + lastIndexOf : new Definition("?Number:searchElement,[fromIndex]"), + every : new Definition("?Boolean:callbackFn,[thisArg]"), + some : new Definition("?Boolean:callbackFn,[thisArg]"), + forEach : new Definition("?Object:callbackFn,[thisArg]"), // should return + map : new Definition("?Array:callbackFn,[thisArg]"), + filter : new Definition("?Array:callbackFn,[thisArg]"), + reduce : new Definition("?Array:callbackFn,[initialValue]"), + reduceRight : new Definition("?Array:callbackFn,[initialValue]"), + $$proto : new Definition("Object") + }, + + /** + * See 15.5.4 Properties of the String Prototype Object + */ + String : { + $$isBuiltin: true, + charAt : new Definition("?String:index"), + charCodeAt : new Definition("?Number:index"), + concat : new Definition("?String:array"), + indexOf : new Definition("?Number:searchString,[start]"), + lastIndexOf : new Definition("?Number:searchString,[start]"), + length : new Definition("Number"), + localeCompare : new Definition("?Number:Object"), + match : new Definition("?Boolean:regexp"), + replace : new Definition("?String:searchValue,replaceValue"), + search : new Definition("?String:regexp"), + slice : new Definition("?String:start,end"), + split : new Definition("?Array:separator,[limit]"), // Array of string + substring : new Definition("?String:start,end"), + toLocaleUpperCase : new Definition("?String:"), + toLowerCase : new Definition("?String:"), + toLocaleLowerCase : new Definition("?String:"), + toUpperCase : new Definition("?String:"), + trim : new Definition("?String:"), + + $$proto : new Definition("Object") + }, + + /** + * See 15.6.4 Properties of the Boolean Prototype Object + */ + Boolean : { + $$isBuiltin: true, + $$proto : new Definition("Object") + }, + + /** + * See 15.7.4 Properties of the Number Prototype Object + */ + Number : { + $$isBuiltin: true, + toExponential : new Definition("?Number:digits"), + toFixed : new Definition("?Number:digits"), + toPrecision : new Definition("?Number:digits"), + // do we want to include NaN, MAX_VALUE, etc? + + $$proto : new Definition("Object") + }, + + /** + * See 15.8.1 15.8.2 Properties and functions of the Math Object + * Note that this object is not used as a prototype to define other objects + */ + Math : { + $$isBuiltin: true, + + // properties + E : new Definition("Number"), + LN2 : new Definition("Number"), + LN10 : new Definition("Number"), + LOG2E : new Definition("Number"), + LOG10E : new Definition("Number"), + PI : new Definition("Number"), + SQRT1_2 : new Definition("Number"), + SQRT2 : new Definition("Number"), + + // Methods + abs : new Definition("?Number:val"), + acos : new Definition("?Number:val"), + asin : new Definition("?Number:val"), + atan : new Definition("?Number:val"), + atan2 : new Definition("?Number:val1,val2"), + ceil : new Definition("?Number:val"), + cos : new Definition("?Number:val"), + exp : new Definition("?Number:val"), + floor : new Definition("?Number:val"), + log : new Definition("?Number:val"), + max : new Definition("?Number:val1,val2"), + min : new Definition("?Number:val1,val2"), + pow : new Definition("?Number:x,y"), + random : new Definition("?Number:"), + round : new Definition("?Number:val"), + sin : new Definition("?Number:val"), + sqrt : new Definition("?Number:val"), + tan : new Definition("?Number:val"), + $$proto : new Definition("Object") + }, + + + /** + * See 15.9.5 Properties of the Date Prototype Object + */ + Date : { + $$isBuiltin: true, + toDateString : new Definition("?String:"), + toTimeString : new Definition("?String:"), + toUTCString : new Definition("?String:"), + toISOString : new Definition("?String:"), + toJSON : new Definition("?Object:key"), + toLocaleDateString : new Definition("?String:"), + toLocaleTimeString : new Definition("?String:"), + + getTime : new Definition("?Number:"), + getTimezoneOffset : new Definition("?Number:"), + + getDay : new Definition("?Number:"), + getUTCDay : new Definition("?Number:"), + getFullYear : new Definition("?Number:"), + getUTCFullYear : new Definition("?Number:"), + getHours : new Definition("?Number:"), + getUTCHours : new Definition("?Number:"), + getMinutes : new Definition("?Number:"), + getUTCMinutes : new Definition("?Number:"), + getSeconds : new Definition("?Number:"), + getUTCSeconds : new Definition("?Number:"), + getMilliseconds : new Definition("?Number:"), + getUTCMilliseconds : new Definition("?Number:"), + getMonth : new Definition("?Number:"), + getUTCMonth : new Definition("?Number:"), + getDate : new Definition("?Number:"), + getUTCDate : new Definition("?Number:"), + + setTime : new Definition("?Number:"), + setTimezoneOffset : new Definition("?Number:"), + + setDay : new Definition("?Number:dayOfWeek"), + setUTCDay : new Definition("?Number:dayOfWeek"), + setFullYear : new Definition("?Number:year,[month],[date]"), + setUTCFullYear : new Definition("?Number:year,[month],[date]"), + setHours : new Definition("?Number:hour,[min],[sec],[ms]"), + setUTCHours : new Definition("?Number:hour,[min],[sec],[ms]"), + setMinutes : new Definition("?Number:min,[sec],[ms]"), + setUTCMinutes : new Definition("?Number:min,[sec],[ms]"), + setSeconds : new Definition("?Number:sec,[ms]"), + setUTCSeconds : new Definition("?Number:sec,[ms]"), + setMilliseconds : new Definition("?Number:ms"), + setUTCMilliseconds : new Definition("?Number:ms"), + setMonth : new Definition("?Number:month,[date]"), + setUTCMonth : new Definition("?Number:month,[date]"), + setDate : new Definition("?Number:date"), + setUTCDate : new Definition("?Number:gate"), + + $$proto : new Definition("Object") + }, + + /** + * See 15.10.6 Properties of the RexExp Prototype Object + */ + RegExp : { + $$isBuiltin: true, +// g : new Definition("Object"), +// i : new Definition("Object"), +// gi : new Definition("Object"), +// m : new Definition("Object"), + source : new Definition("String"), + global : new Definition("Boolean"), + ignoreCase : new Definition("Boolean"), + multiline : new Definition("Boolean"), + lastIndex : new Definition("Boolean"), + + exec : new Definition("?Array:str"), + test : new Definition("?Boolean:str"), + + $$proto : new Definition("Object") + }, + + "?RegExp:" : { + $$isBuiltin: true, + $$proto : new Definition("Function"), + + $1 : new Definition("String"), + $2 : new Definition("String"), + $3 : new Definition("String"), + $4 : new Definition("String"), + $5 : new Definition("String"), + $6 : new Definition("String"), + $7 : new Definition("String"), + $8 : new Definition("String"), + $9 : new Definition("String"), + $_ : new Definition("String"), + $input : new Definition("String"), + input : new Definition("String"), + name : new Definition("String") + }, + + + /** + * See 15.11.4 Properties of the Error Prototype Object + * We don't distinguish between kinds of errors + */ + Error : { + $$isBuiltin: true, + name : new Definition("String"), + message : new Definition("String"), + stack : new Definition("String"), + $$proto : new Definition("Object") + }, + + /** + * See 10.6 Arguments Object + */ + Arguments : { + $$isBuiltin: true, + callee : new Definition("Function"), + length : new Definition("Number"), + + $$proto : new Definition("Object") + }, + + /** + * See 15.12.2 and 15.12.3 Properties of the JSON Object + */ + JSON : { + $$isBuiltin: true, + + parse : new Definition("?Object:str"), + stringify : new Definition("?String:obj"), + $$proto : new Definition("Object") + }, + + "undefined" : { + $$isBuiltin: true + }, + + + /////////////////////////////////////////////////// + // Node specific types + /////////////////////////////////////////////////// + // See http://nodejs.org/api/process.html + Process : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + on: new Definition("?undefined:kind,callback"), + + abort: new Definition("?undefined:"), + stdout: new Definition("Stream"), + stderr: new Definition("Stream"), + stdin: new Definition("Stream"), + argv: new Definition("Array"), // Array. + execPath: new Definition("String"), + chdir: new Definition("?undefined:directory"), + cwd: new Definition("?String:"), + env: new Definition("Object"), + getgid: new Definition("?Number:"), + setgid: new Definition("?undefined:id"), + getuid: new Definition("?Number:"), + setuid: new Definition("?undefined:id"), + version: new Definition("String"), + versions: new Definition("Object"), // TODO create a versions object? + config: new Definition("Object"), + kill: new Definition("?undefined:pid,[signal]"), + pid: new Definition("Number"), + title: new Definition("String"), + arch: new Definition("String"), + platform: new Definition("String"), + memoryUsage: new Definition("?Object:"), + nextTick: new Definition("?undefined:callback"), + umask: new Definition("?undefined:[mask]"), + uptime: new Definition("?Number:"), + hrtime: new Definition("?Array:") // Array. + }, + + // See http://nodejs.org/api/stream.html + // Stream is a wierd one since it is built into the stream module, + // but this module isn't always around, so must explicitly define it. + Stream : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + // combines readable and writable streams + + // readable + + // events + data: new Definition("?undefined:data"), + error: new Definition("?undefined:exception"), + close: new Definition("?undefined:"), + + readable: new Definition("Boolean"), + + setEncoding: new Definition("?undefined:[encoding]"), + pause: new Definition("?undefined:"), + resume: new Definition("?undefined:"), + pipe: new Definition("?undefined:destingation,[options]"), + + // writable + drain: new Definition("?undefined:"), + + writable: new Definition("Boolean"), + + write: new Definition("?undefined:[nuffer]"), + end: new Definition("?undefined:[string],[encoding]"), + destroy: new Definition("?undefined:"), + destroySoon: new Definition("?undefined:") + }, + + /////////////////////////////////////////////////// + // Browser specific types + /////////////////////////////////////////////////// + + // https://developer.mozilla.org/en/DOM/window.screen + Screen : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + availTop : new Definition("Number"), + availLeft : new Definition("Number"), + availHeight : new Definition("Number"), + availWidth : new Definition("Number"), + colorDepth : new Definition("Number"), + height : new Definition("Number"), + left : new Definition("Number"), + pixelDepth : new Definition("Number"), + top : new Definition("Number"), + width : new Definition("Number") + }, + + + // https://developer.mozilla.org/en-US/docs/DOM/window.locationbar + BarInfo : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + visible : new Definition("Boolean") + }, + + // http://w3c-test.org/webperf/specs/NavigationTiming/ + // incomplete + Performance : { + $$isBuiltin: true, + $$proto : new Definition("Object") + }, + + // https://developer.mozilla.org/en/DOM/window.navigator + Navigator : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + // properties + appName : new Definition("String"), + appVersion : new Definition("String"), + connection : new Definition("Connection"), + cookieEnabled : new Definition("Boolean"), + language : new Definition("String"), + mimeTypes : new Definition("MimeTypeArray"), + onLine : new Definition("Boolean"), + oscpu : new Definition("String"), + platform : new Definition("String"), + plugins : new Definition("String"), + userAgent : new Definition("String"), + + // methods + javaEnabled : new Definition("?Boolean:"), + registerContentHandler : new Definition("?undefined:mimType,url,title"), + registerProtocolHandler : new Definition("?undefined:protocol,url,title") + }, + + // (not in MDN) http://www.coursevector.com/dommanual/dom/objects/MimeTypeArray.html + MimeTypeArray : { + $$isBuiltin: true, + length : new Definition("Number"), + item : new Definition("?MimeType:index"), + namedItem : new Definition("?MimeType:name") + }, + + // (not in MDN) http://www.coursevector.com/dommanual/dom/objects/MimeType.html + MimeType : { + $$isBuiltin: true, + description : new Definition("String"), + suffixes : new Definition("String"), + type : new Definition("String"), + enabledPlugin : new Definition("Plugin") + }, + + // (not in MDN) http://www.coursevector.com/dommanual/dom/objects/Plugin.html + Plugin : { + $$isBuiltin: true, + description : new Definition("String"), + fileName : new Definition("String"), + length : new Definition("Number"), + name : new Definition("String"), + item : new Definition("?MimeType:index"), + namedItem : new Definition("?MimeType:name") + }, + + // http://dvcs.w3.org/hg/dap/raw-file/tip/network-api/Overview.html#the-connection-interface + Connection : { + $$isBuiltin: true, + bandwidth : new Definition("Number"), + metered : new Definition("Boolean"), + + onchange : new Definition("Function") + }, + + // http://dev.w3.org/html5/webstorage/#storage-0 + Storage : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + length : new Definition("Number"), + + key : new Definition("?String:idx"), + getItem : new Definition("?String:key"), + setItem : new Definition("?undefined:key,value"), + removeItem : new Definition("?undefined:key"), + clear : new Definition("?undefined:") + }, + + // http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#interface-xmlhttprequest + XMLHttpRequest : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + onreadystatechange : new Definition("EventHandler"), + + // request + open : new Definition("?undefined:method,url,[async],[user],[password]"), + setRequestHeader : new Definition("?undefined:header,value"), + timeout : new Definition("Number"), + withCredentials : new Definition("Boolean"), + upload : new Definition("Object"), // not right + send : new Definition("?undefined:[data]"), + abort : new Definition("?undefined:"), + + // response + getResponseHeader : new Definition("?String:header"), + getAllResponseHeaders : new Definition("?String:"), + overrideMimType : new Definition("Object"), + responseType : new Definition("Object"), // not right + readyState : new Definition("Number"), + response : new Definition("Object"), + responseText : new Definition("String"), + responseXML : new Definition("Document"), + status : new Definition("Number"), + statusText : new Definition("String") + }, + + // http://www.w3.org/TR/workers/ + Worker : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + terminate : new Definition("?undefined:"), + postMessage : new Definition("?undefined:message,[transfer]"), + onmessage : new Definition("?undefined:") + }, + + // http://www.w3.org/TR/workers/#messageport + MessagePort : { + $$isBuiltin: true, + $$proto : new Definition("Object") + }, + + // http://www.whatwg.org/specs/web-apps/current-work/multipage//network.html#websocket + WebSocket : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + onreadystatechange : new Definition("EventHandler"), + onopen : new Definition("EventHandler"), + onerror : new Definition("EventHandler"), + onclose : new Definition("EventHandler"), + + readyState : new Definition("Number"), + extensions : new Definition("String"), + protocol : new Definition("String"), + + close : new Definition("?undefined:[reason]"), + send : new Definition("?undefined:data") + }, + + // https://developer.mozilla.org/en/DOM/Console + Console : { + $$isBuiltin: true, + debug : new Definition("?undefined:msg"), + dir : new Definition("?undefined:obj"), + error : new Definition("?undefined:msg"), + group : new Definition("?undefined:"), + groupCollapsed : new Definition("?undefined:"), + groupEnd : new Definition("?undefined:"), + info : new Definition("?undefined:msg"), + log : new Definition("?undefined:msg"), + time : new Definition("?undefined:timerName"), + timeEnd : new Definition("?undefined:timerName"), + trace : new Definition("?undefined:"), + warn : new Definition("?undefined:msg") + }, + + // TODO FIXADE remove ??? + // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#eventhandler + EventHandler : { + $$isBuiltin: true, + $$proto : new Definition("Object") + }, + + // https://developer.mozilla.org/en/DOM/Event + Event : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + // properties + bubbles : new Definition("Boolean"), + cancelable : new Definition("Boolean"), + currentTarget : new Definition("Object"), + defaultPrevented : new Definition("Boolean"), + eventPhase : new Definition("Number"), // Add constants + explicitOriginalTarget : new Definition("Object"), + originalTarget : new Definition("Object"), + target : new Definition("Object"), + timeStamp : new Definition("Number"), + isTrusted : new Definition("Boolean"), + + // methods + initEvent : new Definition("?undefined:type,bubbles,cancelable"), + preventDefault : new Definition("?undefined:"), + stopImmediatePropagation : new Definition("?undefined:"), + stopPropagation : new Definition("?undefined:") + }, + + "?Event:" : { + $$isBuiltin: true, + $$proto : new Definition("Function"), + + CAPTURING_PHASE : new Definition("Number"), + AT_TARGET : new Definition("Number"), + BUBBLING_PHASE : new Definition("Number") + }, + + // see http://www.w3.org/TR/dom/#documenttype + DocumentType : { + $$isBuiltin: true, + $$proto : new Definition("Node"), + + name : new Definition("String"), + publicId : new Definition("String"), + systemId : new Definition("String"), + + before : new Definition("?undefined:nodeOrString"), + after : new Definition("?undefined:nodeOrString"), + replace : new Definition("?undefined:nodeOrString"), + remove : new Definition("?undefined:") + }, + + // see http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#the-history-interface + History : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + length : new Definition("Number"), + state : new Definition("Object"), + + go : new Definition("?undefined:delta"), + back : new Definition("?undefined:"), + forward : new Definition("?undefined:"), + pushState : new Definition("?undefined:data,title,url"), + replaceState : new Definition("?undefined:data,title,url") + }, + + // see http://www.w3.org/TR/dom/#document (complete) + // see http://www.w3.org/TR/html5/dom.html#documents-in-the-dom (incomplete) + Document : { + $$isBuiltin: true, + $$proto : new Definition("Node"), + + implementation : new Definition("DOMImplementation"), + URL : new Definition("String"), + documentURI : new Definition("String"), + compatMode : new Definition("String"), + characterSet : new Definition("String"), + contentType : new Definition("String"), + + doctype : new Definition("DocumentType"), + documentElement : new Definition("Element"), + + getElementsByTagName : new Definition("?HTMLCollection:localName"), + getElementsByTagNameNS : new Definition("?HTMLCollection:namespace,localName"), + getElementsByClassName : new Definition("?HTMLCollection:classNames"), + getElementById : new Definition("?Element:elementId"), + createElement : new Definition("?Element:elementId"), + createElementNS : new Definition("?Element:namespace,qualifiedName"), + createDocumentFragment : new Definition("?DocumentFragment:"), + createTextNode : new Definition("?Text:data"), + createComment : new Definition("?Comment:data"), + createProcessingInstruction : new Definition("?ProcessingInstruction:target,data"), + importNode : new Definition("?Node:node,[deep]"), + adoptNode : new Definition("?Node:node"), + createEvent : new Definition("?Event:eventInterfaceName"), + createRange : new Definition("?Range:"), + + createNodeIterator : new Definition("?NodeIterator:root,[whatToShow],[filter]"), + createTreeWalker : new Definition("?TreeWalker:root,[whatToShow],[filter]"), + + prepend : new Definition("?undefined:[nodes]"), + append : new Definition("?undefined:[nodes]") + }, + + // see http://www.w3.org/TR/dom/#domimplementation + DOMImplementation : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + createDocumentType : new Definition("?DocumentType:qualifiedName,publicId,systemId"), + createDocument : new Definition("?Document:namespace,qualifiedName,doctype"), + createHTMLDocument : new Definition("?Document:title"), + hasFeature : new Definition("?Boolean:feature") + }, + + // see http://www.w3.org/TR/dom/#node + Node : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + nodeType : new Definition("Number"), + nodeName : new Definition("String"), + baseURI : new Definition("String"), + ownerDocument : new Definition("Document"), + parentNode : new Definition("Node"), + parentElement : new Definition("Element"), + childNodes : new Definition("NodeList"), + firstChild : new Definition("Node"), + lastChild : new Definition("Node"), + previousSibling : new Definition("Node"), + nextSibling : new Definition("Node"), + nodeValue : new Definition("String"), + textContent : new Definition("String"), + + hasChildNodes : new Definition("?Boolean:"), + compareDocumentPosition : new Definition("?Number:other"), + contains : new Definition("?Boolean:other"), + insertBefore : new Definition("?Node:node,child"), + appendChild : new Definition("?Node:node"), + replaceChild : new Definition("?Node:node,child"), + removeChild : new Definition("?Node:node,child"), + normalize : new Definition("?undefined:"), + cloneNode : new Definition("?Node:[deep]"), + isEqualNode : new Definition("?Boolean:node"), + lookupPrefix : new Definition("?String:namespace"), + lookupNamespaceURI : new Definition("?String:prefix"), + isDefaultNamespace : new Definition("?Boolean:namespace") + }, + + // Constants declared on Node + "?Node:" : { + $$isBuiltin: true, + $$proto : new Definition("Function"), + ELEMENT_NODE : new Definition("Number"), + ATTRIBUTE_NODE : new Definition("Number"), + TEXT_NODE : new Definition("Number"), + CDATA_SECTION_NODE : new Definition("Number"), + ENTITY_REFERENCE_NODE : new Definition("Number"), + ENTITY_NODE : new Definition("Number"), + PROCESSING_INSTRUCTION_NODE : new Definition("Number"), + COMMENT_NODE : new Definition("Number"), + DOCUMENT_NODE : new Definition("Number"), + DOCUMENT_TYPE_NODE : new Definition("Number"), + DOCUMENT_FRAGMENT_NODE : new Definition("Number"), + NOTATION_NODE : new Definition("Number"), + + DOCUMENT_POSITION_DISCONNECTED : new Definition("Number"), + DOCUMENT_POSITION_PRECEDING : new Definition("Number"), + DOCUMENT_POSITION_FOLLOWING : new Definition("Number"), + DOCUMENT_POSITION_CONTAINS : new Definition("Number"), + DOCUMENT_POSITION_CONTAINED_BY : new Definition("Number"), + DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC : new Definition("Number") + }, + + // see http://www.w3.org/TR/dom/#element + Element : { + $$isBuiltin: true, + $$proto : new Definition("Node"), + + namespaceURI : new Definition("String"), + prefix : new Definition("String"), + localName : new Definition("String"), + tagName : new Definition("String"), + + id : new Definition("String"), + className : new Definition("String"), + + classList : new Definition("DOMTokenList"), + + attributes : new Definition("Array"), // of attributes + + childElementCount : new Definition("Number"), + + children : new Definition("HTMLCollection"), + firstElementChild : new Definition("Element"), + lastElementChild : new Definition("Element"), + previousElementSibling : new Definition("Element"), + nextElementSibling : new Definition("Element"), + + getAttribute : new Definition("?String:name"), + getAttributeNS : new Definition("?String:namespace,localname"), + setAttribute : new Definition("?undefined:name,value"), + setAttributeNS : new Definition("?undefined:namespace,name,value"), + removeAttribute : new Definition("?undefined:name"), + removeAttributeNS : new Definition("?undefined:namespace,localname"), + hasAttribute : new Definition("?Boolean:name"), + hasAttributeNS : new Definition("?Boolean:namespace,localname"), + + getElementsByTagName : new Definition("?HTMLCollection:localName"), + getElementsByTagNameNS : new Definition("?HTMLCollection:namespace,localName"), + getElementsByClassName : new Definition("?HTMLCollection:classname"), + + prepend : new Definition("?undefined:[nodes]"), + append : new Definition("?undefined:[nodes]"), + before : new Definition("?undefined:[nodes]"), + after : new Definition("?undefined:[nodes]"), + replace : new Definition("?undefined:[nodes]"), + remove : new Definition("?undefined:") + }, + + // see http://www.w3.org/TR/dom/#attr + Attr : { + $$isBuiltin: true, + $$proto : new Definition("Node"), + + isId : new Definition("Boolean"), + name : new Definition("String"), + value : new Definition("String"), + namespaceURI : new Definition("String"), + prefix : new Definition("String"), + localName : new Definition("String") + }, + + // see http://www.w3.org/TR/dom/#interface-nodelist + NodeList : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + item : new Definition("Node"), + length : new Definition("Number") + }, + + // incomplete + DOMApplicationCache : { + $$isBuiltin: true, + $$proto : new Definition("Object") + }, + + // incomplete + CSSStyleDeclaration : { + $$isBuiltin: true, + $$proto : new Definition("Object") + }, + // incomplete + MediaQueryList : { + $$isBuiltin: true, + $$proto : new Definition("Object") + }, + // see http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#dom-location + Location : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + assign : new Definition("?undefined:url"), + replace : new Definition("?undefined:url"), + reload : new Definition("?undefined:"), + + href : new Definition("String"), + protocol : new Definition("String"), + host : new Definition("String"), + hostname : new Definition("String"), + port : new Definition("String"), + pathname : new Definition("String"), + search : new Definition("String"), + hash : new Definition("String") + }, + + // see http://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#selections + Selection : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + anchorNode : new Definition("Node"), + anchorOffset : new Definition("Number"), + focusNode : new Definition("Node"), + focusOffset : new Definition("Number"), + rangeCount : new Definition("Number"), + + isCollapsed : new Definition("Boolean"), + + + collapse : new Definition("?undefined:node,offset"), + collapseToStart : new Definition("?undefined:"), + collapseToEnd : new Definition("?undefined:"), + + extend : new Definition("?undefined:node,offset"), + + selectAllChildren : new Definition("?undefined:node"), + deleteFromDocument : new Definition("?undefined:"), + getRangeAt : new Definition("?Range:index"), + addRange : new Definition("?undefined:range"), + removeRange : new Definition("?undefined:range"), + removeAllRanges : new Definition("?undefined:") + }, + + // see http://www.w3.org/TR/html5/the-html-element.html#the-html-element + // incomplete + HTMLElement : { + $$isBuiltin: true, + $$proto : new Definition("Element"), + + id : new Definition("String"), + title : new Definition("String"), + lang : new Definition("String"), + dir : new Definition("String"), + className : new Definition("String") + }, + + // see http://www.w3.org/TR/html5/the-img-element.html#htmlimageelement + // incomplete + HTMLImageElement : { + $$isBuiltin: true, + $$proto : new Definition("HTMLElement") + }, + + // incomplete + HTMLOptionElement : { + $$isBuiltin: true, + $$proto : new Definition("HTMLElement") + }, + + // http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75708506 + HTMLCollection : { + $$isBuiltin: true, + $$proto : new Definition("Object"), + length : new Definition("Number"), + item : new Definition("?Element:index"), + namedItem : new Definition("?Element:name") + }, + + // incomplete + NodeIterator : { + $$isBuiltin: true, + $$proto : new Definition("Object") + }, + + // incomplete + TreeWalker : { + $$isBuiltin: true, + $$proto : new Definition("Object") + }, + + // http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#interface-documentfragment + DocumentFragment : { + $$isBuiltin: true, + $$proto : new Definition("Node"), + + prepend : new Definition("?undefined:[nodes]"), + append : new Definition("?undefined:[nodes]") + }, + + // incomplete + Text : { + $$isBuiltin: true, + $$proto : new Definition("Node") + }, + + // incomplete + ProcessingInstruction : { + $$isBuiltin: true, + $$proto : new Definition("Node") + }, + + // incomplete + Comment : { + $$isBuiltin: true, + $$proto : new Definition("Node") + }, + + // see http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#ranges + Range: { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + startContainer : new Definition("Node"), + startOffset : new Definition("Number"), + endContainer : new Definition("Node"), + endOffset : new Definition("Number"), + collapsed : new Definition("Boolean"), + commonAncestorContainer : new Definition("Node"), + + setStart : new Definition("?undefined:refNode,offset"), + setEnd : new Definition("?undefined:refNode,offset"), + setStartBefore : new Definition("?undefined:refNode"), + setStartAfter : new Definition("?undefined:refNode"), + setEndBefore : new Definition("?undefined:refNode"), + setEndAfter : new Definition("?undefined:refNode"), + collapse : new Definition("?undefined:toStart"), + selectNode : new Definition("?undefined:refNode"), + selectNodeContents : new Definition("?undefined:refNode"), + + compareBoundaryPoints : new Definition("?Number:how,sourceRange"), + + deleteContents : new Definition("?undefined:"), + extractContents : new Definition("?DocumentFragment:"), + cloneContents : new Definition("?DocumentFragment:"), + insertNode : new Definition("?undefined:node"), + surroundContents : new Definition("?undefined:nodeParent"), + + cloneRange : new Definition("?Range:"), + detach : new Definition("?undefined:"), + + + isPointInRange : new Definition("?Boolean:node,offset"), + comparePoint : new Definition("?Number:node,offset"), + + intersectsNode : new Definition("?Boolean:node") + }, + + "?Range:" : { + $$isBuiltin: true, + START_TO_START : new Definition("Number"), + START_TO_END : new Definition("Number"), + END_TO_END : new Definition("Number"), + END_TO_START : new Definition("Number") + }, + + + // incomplete + DOMTokenList: { + $$isBuiltin: true, + $$proto : new Definition("Object"), + + length : new Definition("Number"), + + item : new Definition("?String:index"), + contains : new Definition("?Boolean:token"), + add : new Definition("?undefined:token"), + remove : new Definition("?undefined:token"), + toggle : new Definition("?Boolean:token") + } + +// HTML constructors +// http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-33759296 +/* +HTMLVideoElement +HTMLAppletElement +HTMLCollection +HTMLOutputElement +HTMLQuoteElement +HTMLFrameElement +HTMLTableSectionElement +HTMLModElement +HTMLTableCaptionElement +HTMLCanvasElement +HTMLOptGroupElement +HTMLLinkElement +HTMLImageElement +HTMLBRElement +HTMLProgressElement +HTMLParagraphElement +HTMLScriptElement +HTMLOListElement +HTMLTableCellElement +HTMLTextAreaElement +HTMLUListElement +HTMLMarqueeElement +HTMLFieldSetElement +HTMLLIElement +HTMLTableElement +HTMLButtonElement +HTMLAnchorElement +HTMLAllCollection +HTMLMetaElement +HTMLLabelElement +HTMLMenuElement +HTMLMapElement +HTMLParamElement +HTMLTableColElement +HTMLTableRowElement +HTMLDocument +HTMLSpanElement +HTMLBaseFontElement +HTMLEmbedElement +HTMLDivElement +HTMLBaseElement +HTMLHeadElement +HTMLTitleElement +HTMLDirectoryElement +HTMLUnknownElement +HTMLHtmlElement +HTMLHRElement +HTMLInputElement +HTMLDataListElement +HTMLStyleElement +HTMLSourceElement +HTMLOptionElement +HTMLFontElement +HTMLElement +HTMLBodyElement +HTMLFormElement +HTMLHeadingElement +HTMLSelectElement +HTMLPreElement +HTMLIFrameElement +HTMLMediaElement +HTMLLegendElement +HTMLObjectElement +HTMLDListElement +HTMLAudioElement +HTMLAreaElement +HTMLFrameSetElement +HTMLMeterElement +HTMLKeygenElement +*/ +// SVG constructors +// http://www.w3.org/TR/SVG11/struct.html#NewDocument +/* +SVGScriptElement +SVGCircleElement +SVGTitleElement +SVGFEDistantLightElement +SVGGElement +SVGAnimatedString +SVGFEConvolveMatrixElement +SVGTransform +SVGAltGlyphDefElement +SVGAnimatedLengthList +SVGCursorElement +SVGAnimateColorElement +SVGPathSegCurvetoQuadraticSmoothAbs +SVGDefsElement +SVGAnimateElement +SVGPathSegLinetoVerticalAbs +SVGAnimatedBoolean +SVGVKernElement +SVGElement +SVGEllipseElement +SVGForeignObjectElement +SVGColor +SVGFEPointLightElement +SVGMissingGlyphElement +SVGPathSegCurvetoCubicRel +SVGPathSegMovetoRel +SVGFEDisplacementMapElement +SVGPathSegArcRel +SVGAElement +SVGFETurbulenceElement +SVGMetadataElement +SVGTextElement +SVGElementInstanceList +SVGFEBlendElement +SVGTSpanElement +SVGFESpecularLightingElement +SVGPathSegArcAbs +SVGZoomEvent +SVGSVGElement +SVGPathSegLinetoHorizontalRel +SVGFEOffsetElement +SVGAltGlyphItemElement +SVGPaint +SVGException +SVGLengthList +SVGFontFaceUriElement +SVGPathSegLinetoAbs +SVGMarkerElement +SVGStyleElement +SVGAnimatedRect +SVGFilterElement +SVGFEFuncGElement +SVGAnimatedNumberList +SVGPathSegLinetoHorizontalAbs +SVGZoomAndPan +SVGFEImageElement +SVGAnimatedPreserveAspectRatio +SVGPathSegLinetoVerticalRel +SVGAltGlyphElement +SVGSetElement +SVGPathSegCurvetoCubicAbs +SVGRect +SVGPathSegClosePath +SVGFEGaussianBlurElement +SVGAngle +SVGViewElement +SVGMatrix +SVGPreserveAspectRatio +SVGTextPathElement +SVGRenderingIntent +SVGFEFloodElement +SVGAnimateTransformElement +SVGFEMergeNodeElement +SVGPoint +SVGTRefElement +SVGFESpotLightElement +SVGLinearGradientElement +SVGPathSegList +SVGTextContentElement +SVGPointList +SVGSwitchElement +SVGPathSegCurvetoQuadraticSmoothRel +SVGFontFaceElement +SVGLineElement +SVGLength +SVGFECompositeElement +SVGDocument +SVGGlyphElement +SVGFontFaceNameElement +SVGFEMergeElement +SVGPathSegCurvetoCubicSmoothRel +SVGAnimatedInteger +SVGAnimatedNumber +SVGAnimateMotionElement +SVGStopElement +SVGUseElement +SVGFontElement +SVGGradientElement +SVGPathSegLinetoRel +SVGPathSegCurvetoQuadraticAbs +SVGAnimatedEnumeration +SVGNumber +SVGTextPositioningElement +SVGComponentTransferFunctionElement +SVGFEDiffuseLightingElement +SVGStringList +SVGRadialGradientElement +SVGPathElement +SVGMaskElement +SVGFEFuncBElement +SVGPolygonElement +SVGGlyphRefElement +SVGFEColorMatrixElement +SVGElementInstance +SVGFontFaceSrcElement +SVGAnimatedAngle +SVGFontFaceFormatElement +SVGHKernElement +SVGPolylineElement +SVGAnimatedTransformList +SVGFEFuncRElement +SVGDescElement +SVGAnimatedLength +SVGSymbolElement +SVGNumberList +SVGViewSpec +SVGPathSegCurvetoCubicSmoothAbs +SVGMPathElement +SVGPatternElement +SVGPathSegCurvetoQuadraticRel +SVGFEComponentTransferElement +SVGRectElement +SVGTransformList +SVGFETileElement +SVGFEDropShadowElement +SVGUnitTypes +SVGPathSegMovetoAbs +SVGClipPathElement +SVGFEMorphologyElement +SVGImageElement +SVGPathSeg +SVGFEFuncAElement +*/ + }; + + var protoLength = "~proto".length; + return { + Types : Types, + Definition : Definition, + + // now some functions that handle types signatures, styling, and parsing + + /** constant that defines generated type name prefixes */ + GEN_NAME : "gen~", + + + // type parsing + isArrayType : function(typeName) { + return typeName.substr(0, "Array.<".length) === "Array.<"; + }, + + isFunctionOrConstructor : function(typeName) { + return typeName.charAt(0) === "?" || typeName.charAt(0) === "*"; + }, + + isPrototype : function(typeName) { + return typeName.charAt(0) === "*" && typeName.substr( - protoLength, protoLength) === "~proto"; + }, + + findReturnTypeEnd : function(fnType) { + if (this.isFunctionOrConstructor(fnType)) { + // walk the string and for every ? or *, find the corresponding :, until we reach the + // : for the first ? or * + var depth = 1; + var index = 1; + var len = fnType.length; + + while (index < len) { + if (this.isFunctionOrConstructor(fnType.charAt(index))) { + depth++; + } else if (fnType.charAt(index) === ":") { + depth--; + } + + if (depth === 0) { + // found it + return index; + } + + index++; + } + } + return -1; + }, + + removeParameters : function(fnType) { + var index = this.findReturnTypeEnd(fnType); + if (index >= 0) { + return fnType.substring(0,index+1); + } + // didn't find a matching ":" (ie- invalid type) + // or just not a function type + return fnType; + }, + + /** + * if the type passed in is a function type, extracts the return type + * otherwise returns as is + */ + extractReturnType : function(fnType) { + var index = this.findReturnTypeEnd(fnType); + if (index >= 0) { + return fnType.substring(1,index); + } + // didn't find a matching ":" (ie- invalid type) + // or just not a function type + return fnType; + }, + + /** + * returns a parameterized array type with the given type parameter + */ + parameterizeArray : function(parameterType) { + return "Array.<" + parameterType + ">"; + }, + + /** + * If this is a parameterized array type, then extracts the type, + * Otherwise object + */ + extractArrayParameterType : function (arrayType) { + if (arrayType.substr(0, "Array.<".length) === "Array.<" && arrayType.substr(-1, 1) === ">") { + return arrayType.substring("Array.<".length, arrayType.length -1); + } else { + return "Object"; + } + }, + + parseJSDocComment : function(docComment) { + var result = { }; + result.params = {}; + if (docComment) { + var commentText = docComment.value; + try { + var rawresult = doctrine.parse("/*" + commentText + "*/", {unwrap : true, tags : ['param', 'type', 'return']}); + // transform result into something more manageable + var rawtags = rawresult.tags; + if (rawtags) { + for (var i = 0; i < rawtags.length; i++) { + switch (rawtags[i].title) { + case "typedef": + case "define": + case "type": + result.type = rawtags[i].type; + break; + case "return": + result.rturn = rawtags[i].type; + break; + case "param": + // remove square brackets + var name = rawtags[i].name; + if (name.charAt(0) === '[' && name.charAt(name.length -1) === ']') { + name = name.substring(1, name.length-1); + } + result.params[name] = rawtags[i].type; + break; + } + } + } + } catch (e) { + scriptedLogger.error(e.message, "CONTENT_ASSIST"); + scriptedLogger.error(e.stack, "CONTENT_ASSIST"); + } + } + return result; + }, + + /** + * Best effort to recursively convert from a jsdoc type specification to a scripted type name. + * + * See here: https://developers.google.com/closure/compiler/docs/js-for-compiler + * should handle: + NullableLiteral + AllLiteral + NullLiteral + UndefinedLiteral + VoidLiteral + UnionType + ArrayType + RecordType + FieldType + FunctionType + ParameterType + RestType + NonNullableType + OptionalType + NullableType + NameExpression + TypeApplication + * @return {String} if the type is found, then return string, otherwise null + */ + convertJsDocType : function(jsdocType, env) { + var allTypes = env.getAllTypes(); + if (!jsdocType) { + return null; + } + + var i; + switch (jsdocType.type) { + case 'NullableLiteral': + case 'AllLiteral': + case 'NullLiteral': + return "Object"; + + case 'UndefinedLiteral': + case 'VoidLiteral': + return "undefined"; + + case 'UnionType': + // TODO no direct handling of union types + // for now, just return the first of the union + if (jsdocType.elements && jsdocType.elements.length > 0) { + return this.convertJsDocType(jsdocType.elements[0], env); + } + return "Object"; + + case 'RestType': + return "Array.<" + this.convertJsDocType(jsdocType.expression, env) + ">"; + case 'ArrayType': + if (jsdocType.elements && jsdocType.elements.length > 0) { + // assume array type is type of first element, not correct, but close enough + return "Array.<" + this.convertJsDocType(jsdocType.elements[0], env) + ">"; + } + return "Array"; + + case 'FunctionType': + var ret = this.convertJsDocType(jsdocType.result, env); + if (!ret) { + ret = "Object"; + } + var params = []; + if (jsdocType.params) { + for (i = 0; i < jsdocType.params.length; i++) { + // this means that if no name is used, then the type name is used (if a simple type) + var param = jsdocType.params[i].name; + if (!param) { + param = 'arg'+i; + } + var paramType = ""; + if (jsdocType.params[i].expression) { + paramType = "/" + this.convertJsDocType(jsdocType.params[i].expression, env); + } + params.push(param + paramType); + } + } + // TODO FIXADE must also handle @constructor + var funcConstr; + if (jsdocType['new'] && jsdocType['this']) { + // this is actually a constructor + var maybeRet = this.convertJsDocType(jsdocType['this'], env); + if (maybeRet) { + ret = maybeRet; + } + funcConstr = "*"; + } else { + funcConstr = "?"; + } + return funcConstr + ret + ":" + params.join(','); + + case 'TypeApplication': + var expr = this.convertJsDocType(jsdocType.expression, env); + if (expr === "Array" && jsdocType.applications && jsdocType.applications.length > 0) { + // only parameterize arrays not handling objects yet + return "Array.<" + this.convertJsDocType(jsdocType.applications[0], env) + ">"; + } + return expr; + case 'ParameterType': + case 'NonNullableType': + case 'OptionalType': + case 'NullableType': + return this.convertJsDocType(jsdocType.expression, env); + + case 'NameExpression': + var name = jsdocType.name; + name = name.trim(); + if (allTypes[name]) { + return name; + } else { + var capType = name[0].toUpperCase() + name.substring(1); + if (allTypes[capType]) { + return capType; + } + } + return null; + case 'RecordType': + var fields = { }; + for (i = 0; i < jsdocType.fields.length; i++) { + var field = jsdocType.fields[i]; + var fieldType = this.convertJsDocType(field, env); + fields[field.key] = fieldType ? fieldType : "Object"; + } + // create a new type to store the record + var obj = env.newFleetingObject(); + for (var prop in fields) { + if (fields.hasOwnProperty(prop)) { + // add the variable to the new object, which happens to be the top-level scope + env.addVariable(prop, obj, fields[prop]); + } + } + return obj; + case 'FieldType': + return this.convertJsDocType(jsdocType.value, env); + } + return null; + }, + + // type styling + styleAsProperty : function(prop, useHtml) { + return useHtml ? "" + prop + "": prop; + }, + styleAsType : function(type, useHtml) { + return useHtml ? "" + type + "": type; + }, + styleAsOther : function(text, useHtml) { + return useHtml ? "" + text + "": text; + }, + + /** + * creates a human readable type name from the name given + */ + createReadableType : function(typeName, env, useFunctionSig, depth, useHtml) { + depth = depth || 0; + var first = typeName.charAt(0); + if (first === "?" || first === "*") { + // a function + var returnEnd = this.findReturnTypeEnd(typeName); + if (returnEnd === -1) { + returnEnd = typeName.length; + } + var funType = typeName.substring(1, returnEnd); + if (useFunctionSig) { + // convert into a function signature + var prefix = first === "?" ? "" : "new"; + var args = typeName.substring(returnEnd+1, typeName.length); + var argsSigs = []; + var self = this; + args.split(",").forEach(function(arg) { + var typeSplit = arg.indexOf("/"); + var argName = typeSplit > 0 ? arg.substring(0, typeSplit) : arg; + argName = self.styleAsProperty(argName, useHtml); + var argSig = typeSplit > 0 ? arg.substring(typeSplit + 1) : ""; + + if (argSig) { + var sig = self.createReadableType(argSig, env, true, depth+1, useHtml); + if (sig === "{ }") { + argsSigs.push(argName); + } else { + argsSigs.push(argName + ":" + sig); + } + } else { + argsSigs.push(argName); + } + }); + + // note the use of the ⇒ ⇒ char here. Must use the char directly since js_render will format it otherwise + return prefix + "(" + argsSigs.join(", ") + + (useHtml ? ")
" + proposalUtils.repeatChar("  ", depth+1) + "⇒ " : ") ⇒ ") + + this.createReadableType(funType, env, true, depth + 1, useHtml); + } else { + // use the return type + return this.createReadableType(funType, env, true, depth, useHtml); + } + } else if (typeName.indexOf(this.GEN_NAME) === 0) { + // a generated object + if (depth > 1) { + // don't show inner types + return this.styleAsOther("{...}", useHtml); + } + + // create a summary + var type = env.findType(typeName); + var res = "{ "; + var props = []; + for (var val in type) { + if (type.hasOwnProperty(val) && val !== "$$proto") { + var name; + // don't show inner objects + name = this.createReadableType(type[val].typeName, env, true, depth + 1, useHtml); + props.push((useHtml ? "
" + proposalUtils.repeatChar("    ", depth+1) : "" ) + + this.styleAsProperty(val, useHtml) + ":" + name); + } + } + res += props.join(", "); + return res + " }"; + } else if (this.isArrayType(typeName)) { + var typeParameter = this.extractArrayParameterType(typeName); + if (typeParameter !== "Object") { + typeName = this.createReadableType(typeParameter, env, true, depth+1, useHtml) + "[]"; + } else { + typeName = "[]"; + } + return typeName; + } else { + return this.styleAsType(typeName, useHtml); + } + } + }; +}); diff --git a/scripts/lib/esprima-master/assets/orion/customeditor.js b/scripts/lib/esprima-master/assets/orion/customeditor.js new file mode 100755 index 0000000..9358c16 --- /dev/null +++ b/scripts/lib/esprima-master/assets/orion/customeditor.js @@ -0,0 +1,211 @@ +/******************************************************************************* + * @license + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials are made + * available under the terms of the Eclipse Public License v1.0 + * (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution + * License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +/*globals define */ + +define('custom/editor', [ //$NON-NLS-0$ + + "orion/editor/textView", //$NON-NLS-0$ + "orion/editor/textModel", //$NON-NLS-0$ + "orion/editor/projectionTextModel", //$NON-NLS-0$ + "orion/editor/eventTarget", //$NON-NLS-0$ + "orion/editor/keyBinding", //$NON-NLS-0$ + "orion/editor/rulers", //$NON-NLS-0$ + "orion/editor/annotations", //$NON-NLS-0$ + "orion/editor/tooltip", //$NON-NLS-0$ + "orion/editor/undoStack", //$NON-NLS-0$ + "orion/editor/textDND", //$NON-NLS-0$ + + "orion/editor/editor", //$NON-NLS-0$ + "orion/editor/editorFeatures", //$NON-NLS-0$ + + "orion/editor/contentAssist", //$NON-NLS-0$ + + "examples/editor/textStyler" //$NON-NLS-0$ +], function(mTextView, mTextModel, mProjModel, mEventTarget, mKeyBinding, mRulers, mAnnotations, mTooltip, mUndoStack, mTextDND, mEditor, mEditorFeatures, mContentAssist, mTextStyler) { + + /** @private */ + function getTextFromElement(element) { + var document = element.ownerDocument; + var window = document.defaultView || document.parentWindow; + if (!window.getSelection) { + return element.innerText || element.textContent; + } + var newRange = document.createRange(); + newRange.selectNode(element); + var selection = window.getSelection(); + var oldRanges = [], i; + for (i = 0; i < selection.rangeCount; i++) { + oldRanges.push(selection.getRangeAt(i)); + } + selection.removeAllRanges(); + selection.addRange(newRange); + var text = selection.toString(); + selection.removeAllRanges(); + for (i = 0; i < oldRanges.length; i++) { + selection.addRange(oldRanges[i]); + } + return text; + } + + /** + * @class This object describes the options for edit. + * @name orion.editor.EditOptions + * + * @property {String|DOMElement} parent the parent element for the view, it can be either a DOM element or an ID for a DOM element. + * @property {Boolean} [readonly=false] whether or not the view is read-only. + * @property {Boolean} [fullSelection=true] whether or not the view is in full selection mode. + * @property {Boolean} [tabMode=true] whether or not the tab keypress is consumed by the view or is used for focus traversal. + * @property {Boolean} [expandTab=false] whether or not the tab key inserts white spaces. + * @property {String} [themeClass] the CSS class for the view theming. + * @property {Number} [tabSize=4] The number of spaces in a tab. + * @property {Boolean} [wrapMode=false] whether or not the view wraps lines. + * @property {Function} [statusReporter] a status reporter. + * @property {String} [title=""] the editor title. + * @property {String} [contents=""] the editor contents. + * @property {String} [lang] the styler language. Plain text by default. + * @property {Boolean} [showLinesRuler=true] whether or not the lines ruler is shown. + * @property {Boolean} [showAnnotationRuler=true] whether or not the annotation ruler is shown. + * @property {Boolean} [showOverviewRuler=true] whether or not the overview ruler is shown. + * @property {Boolean} [showFoldingRuler=true] whether or not the folding ruler is shown. + */ + /** + * Creates an editor instance configured with the given options. + * + * @param {orion.editor.EditOptions} options the editor options. + */ + function edit(options) { + var parent = options.parent; + if (!parent) { parent = "editor"; } //$NON-NLS-0$ + if (typeof(parent) === "string") { //$NON-NLS-0$ + parent = (options.document || document).getElementById(parent); + } + if (!parent) { + if (options.className) { + var parents = (options.document || document).getElementsByClassName(options.className); + if (parents) { + options.className = undefined; + var editors = []; + for (var i = 0; i < parents.length; i++) { + options.parent = parents[i]; + editors.push(edit(options)); + } + return editors; + } + } + } + if (!parent) { throw "no parent"; } //$NON-NLS-0$ + + var textViewFactory = function() { + return new mTextView.TextView({ + parent: parent, + model: new mProjModel.ProjectionTextModel(new mTextModel.TextModel("")), + tabSize: options.tabSize ? options.tabSize : 4, + readonly: options.readonly, + fullSelection: options.fullSelection, + tabMode: options.tabMode, + expandTab: options.expandTab, + themeClass: options.themeClass, + wrapMode: options.wrapMode + }); + }; + + var contentAssist, contentAssistFactory; + if (!options.readonly && options.contentassist) { + contentAssistFactory = { + createContentAssistMode: function(editor) { + contentAssist = new mContentAssist.ContentAssist(editor.getTextView()); + var contentAssistWidget = new mContentAssist.ContentAssistWidget(contentAssist); + return new mContentAssist.ContentAssistMode(contentAssist, contentAssistWidget); + } + }; + } + + // Canned highlighters for js, java, and css. Grammar-based highlighter for html + var syntaxHighlighter = { + styler: null, + + highlight: function(lang, editor) { + if (this.styler) { + this.styler.destroy(); + this.styler = null; + } + if (lang) { + var textView = editor.getTextView(); + var annotationModel = editor.getAnnotationModel(); + this.styler = new mTextStyler.TextStyler(textView, lang, annotationModel); + editor.setFoldingRulerVisible(options.showFoldingRuler === undefined || options.showFoldingRuler); + } + } + }; + + var keyBindingFactory = function(editor, keyModeStack, undoStack, contentAssist) { + + // Create keybindings for generic editing + var genericBindings = new mEditorFeatures.TextActions(editor, undoStack); + keyModeStack.push(genericBindings); + + // create keybindings for source editing + var codeBindings = new mEditorFeatures.SourceCodeActions(editor, undoStack, contentAssist); + keyModeStack.push(codeBindings); + }; + + var editor = new mEditor.Editor({ + textViewFactory: textViewFactory, + undoStackFactory: new mEditorFeatures.UndoFactory(), + annotationFactory: new mEditorFeatures.AnnotationFactory(), + lineNumberRulerFactory: new mEditorFeatures.LineNumberRulerFactory(), + foldingRulerFactory: new mEditorFeatures.FoldingRulerFactory(), + textDNDFactory: new mEditorFeatures.TextDNDFactory(), + contentAssistFactory: contentAssistFactory, + keyBindingFactory: keyBindingFactory, + statusReporter: options.statusReporter, + domNode: parent + }); + + var contents = options.contents; + if (contents === undefined) { + contents = getTextFromElement(parent); + } + if (!contents) { contents=""; } + + editor.installTextView(); + editor.setLineNumberRulerVisible(options.showLinesRuler === undefined || options.showLinesRuler); + editor.setAnnotationRulerVisible(options.showAnnotationRuler === undefined || options.showFoldingRuler); + editor.setOverviewRulerVisible(options.showOverviewRuler === undefined || options.showOverviewRuler); + editor.setFoldingRulerVisible(options.showFoldingRuler === undefined || options.showFoldingRuler); + editor.setInput(options.title, null, contents); + syntaxHighlighter.highlight(options.lang, editor); + if (contentAssist) { + var mJSContentAssist = require("plugins/esprima/esprimaJsContentAssist"); + var jsTemplateContentAssistProvider = new mJSContentAssist.EsprimaJavaScriptContentAssistProvider(); + contentAssist.addEventListener("Activating", function() { //$NON-NLS-0$ + contentAssist.setProviders([jsTemplateContentAssistProvider]); + }); + } + + editor.addErrorMarker = function (pos, description) { + var annotationModel = editor.getAnnotationModel(); + var marker = mAnnotations.AnnotationType.createAnnotation(mAnnotations.AnnotationType.ANNOTATION_WARNING, pos, pos, description); + annotationModel.addAnnotation(marker); + }; + + editor.removeAllErrorMarkers = function () { + var annotationModel = editor.getAnnotationModel(); + annotationModel.removeAnnotations(mAnnotations.AnnotationType.ANNOTATION_WARNING); + }; + + return editor; + } + + return edit; +}); diff --git a/scripts/lib/esprima-master/assets/prettify/prettify.css b/scripts/lib/esprima-master/assets/prettify/prettify.css new file mode 100755 index 0000000..d44b3a2 --- /dev/null +++ b/scripts/lib/esprima-master/assets/prettify/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} \ No newline at end of file diff --git a/scripts/lib/esprima-master/assets/prettify/prettify.js b/scripts/lib/esprima-master/assets/prettify/prettify.js new file mode 100755 index 0000000..eef5ad7 --- /dev/null +++ b/scripts/lib/esprima-master/assets/prettify/prettify.js @@ -0,0 +1,28 @@ +var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; +(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= +[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), +l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, +q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, +q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, +"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), +a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} +for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], +"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], +H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], +J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ +I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), +["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", +/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), +["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", +hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= +!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p-1;e-=1)if(b[e]&&c(b[e],e,b))break}}function y(b,c){for(var e in b)if(b.hasOwnProperty(e)&&c(b[e],e))break}function K(b,c,e,i){c&&y(c,function(c,j){if(e||!b.hasOwnProperty(j))i&&typeof c!=="string"?(b[j]||(b[j]={}),K(b[j],c,e,i)):b[j]=c});return b}function s(b, +c){return function(){return c.apply(b,arguments)}}function Z(b){if(!b)return b;var c=Y;q(b.split("."),function(b){c=c[b]});return c}function $(b,c,e){return function(){var i=fa.call(arguments,0),g;if(e&&x(g=i[i.length-1]))g.__requireJsBuild=!0;i.push(c);return b.apply(null,i)}}function aa(b,c,e){q([["toUrl"],["undef"],["defined","requireDefined"],["specified","requireSpecified"]],function(i){var g=i[1]||i[0];b[i[0]]=c?$(c[g],e):function(){var b=z[O];return b[g].apply(b,arguments)}})}function H(b, +c,e,i){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=i;if(e)c.originalError=e;return c}function ga(){if(I&&I.readyState==="interactive")return I;N(document.getElementsByTagName("script"),function(b){if(b.readyState==="interactive")return I=b});return I}var ha=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ia=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,ba=/\.js$/,ja=/^\.\//,J=Object.prototype.toString,A=Array.prototype,fa=A.slice,ka=A.splice,w=!!(typeof window!== +"undefined"&&navigator&&document),ca=!w&&typeof importScripts!=="undefined",la=w&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,O="_",S=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",z={},p={},P=[],L=!1,j,t,C,u,D,I,E,da,ea;if(typeof define==="undefined"){if(typeof requirejs!=="undefined"){if(x(requirejs))return;p=requirejs;requirejs=void 0}typeof require!=="undefined"&&!x(require)&&(p=require,require=void 0);j=requirejs=function(b,c,e,i){var g=O,r;!G(b)&& +typeof b!=="string"&&(r=b,G(c)?(b=c,c=e,e=i):b=[]);if(r&&r.context)g=r.context;(i=z[g])||(i=z[g]=j.s.newContext(g));r&&i.configure(r);return i.require(b,c,e)};j.config=function(b){return j(b)};require||(require=j);j.version="2.0.4";j.jsExtRegExp=/^\/|:|\?|\.js$/;j.isBrowser=w;A=j.s={contexts:z,newContext:function(b){function c(a,d,o){var l=d&&d.split("/"),f=l,b=k.map,c=b&&b["*"],e,g,h;if(a&&a.charAt(0)===".")if(d){f=k.pkgs[d]?l=[d]:l.slice(0,l.length-1);d=a=f.concat(a.split("/"));for(f=0;d[f];f+= +1)if(e=d[f],e===".")d.splice(f,1),f-=1;else if(e==="..")if(f===1&&(d[2]===".."||d[0]===".."))break;else f>0&&(d.splice(f-1,2),f-=2);f=k.pkgs[d=a[0]];a=a.join("/");f&&a===d+"/"+f.main&&(a=d)}else a.indexOf("./")===0&&(a=a.substring(2));if(o&&(l||c)&&b){d=a.split("/");for(f=d.length;f>0;f-=1){g=d.slice(0,f).join("/");if(l)for(e=l.length;e>0;e-=1)if(o=b[l.slice(0,e).join("/")])if(o=o[g]){h=o;break}!h&&c&&c[g]&&(h=c[g]);if(h){d.splice(0,f,h);a=d.join("/");break}}}return a}function e(a){w&&q(document.getElementsByTagName("script"), +function(d){if(d.getAttribute("data-requiremodule")===a&&d.getAttribute("data-requirecontext")===h.contextName)return d.parentNode.removeChild(d),!0})}function i(a){var d=k.paths[a];if(d&&G(d)&&d.length>1)return e(a),d.shift(),h.undef(a),h.require([a]),!0}function g(a,d,o,b){var f=a?a.indexOf("!"):-1,v=null,e=d?d.name:null,g=a,i=!0,j="",k,m;a||(i=!1,a="_@r"+(N+=1));f!==-1&&(v=a.substring(0,f),a=a.substring(f+1,a.length));v&&(v=c(v,e,b),m=n[v]);a&&(v?j=m&&m.normalize?m.normalize(a,function(a){return c(a, +e,b)}):c(a,e,b):(j=c(a,e,b),k=h.nameToUrl(j)));a=v&&!m&&!o?"_unnormalized"+(O+=1):"";return{prefix:v,name:j,parentMap:d,unnormalized:!!a,url:k,originalName:g,isDefine:i,id:(v?v+"!"+j:j)+a}}function r(a){var d=a.id,o=m[d];o||(o=m[d]=new h.Module(a));return o}function p(a,d,o){var b=a.id,f=m[b];if(n.hasOwnProperty(b)&&(!f||f.defineEmitComplete))d==="defined"&&o(n[b]);else r(a).on(d,o)}function B(a,d){var b=a.requireModules,l=!1;if(d)d(a);else if(q(b,function(d){if(d=m[d])d.error=a,d.events.error&&(l= +!0,d.emit("error",a))}),!l)j.onError(a)}function u(){P.length&&(ka.apply(F,[F.length-1,0].concat(P)),P=[])}function t(a,d,b){a=a&&a.map;d=$(b||h.require,a,d);aa(d,h,a);d.isBrowser=w;return d}function z(a){delete m[a];q(M,function(d,b){if(d.map.id===a)return M.splice(b,1),d.defined||(h.waitCount-=1),!0})}function A(a,d){var b=a.map.id,l=a.depMaps,f;if(a.inited){if(d[b])return a;d[b]=!0;q(l,function(a){if(a=m[a.id])return!a.inited||!a.enabled?(f=null,delete d[b],!0):f=A(a,K({},d))});return f}}function C(a, +d,b){var l=a.map.id,f=a.depMaps;if(a.inited&&a.map.isDefine){if(d[l])return n[l];d[l]=a;q(f,function(f){var f=f.id,c=m[f];!Q[f]&&c&&(!c.inited||!c.enabled?b[l]=!0:(c=C(c,d,b),b[f]||a.defineDepById(f,c)))});a.check(!0);return n[l]}}function D(a){a.check()}function E(){var a=k.waitSeconds*1E3,d=a&&h.startTime+a<(new Date).getTime(),b=[],l=!1,f=!0,c,g,j;if(!T){T=!0;y(m,function(a){c=a.map;g=c.id;if(a.enabled&&!a.error)if(!a.inited&&d)i(g)?l=j=!0:(b.push(g),e(g));else if(!a.inited&&a.fetched&&c.isDefine&& +(l=!0,!c.prefix))return f=!1});if(d&&b.length)return a=H("timeout","Load timeout for modules: "+b,null,b),a.contextName=h.contextName,B(a);f&&(q(M,function(a){if(!a.defined){var a=A(a,{}),d={};a&&(C(a,d,{}),y(d,D))}}),y(m,D));if((!d||j)&&l)if((w||ca)&&!U)U=setTimeout(function(){U=0;E()},50);T=!1}}function V(a){r(g(a[0],null,!0)).init(a[1],a[2])}function J(a){var a=a.currentTarget||a.srcElement,d=h.onScriptLoad;a.detachEvent&&!S?a.detachEvent("onreadystatechange",d):a.removeEventListener("load",d, +!1);d=h.onScriptError;a.detachEvent&&!S||a.removeEventListener("error",d,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}var k={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},shim:{}},m={},W={},F=[],n={},R={},N=1,O=1,M=[],T,X,h,Q,U;Q={require:function(a){return t(a)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports=n[a.map.id]={}},module:function(a){return a.module={id:a.map.id,uri:a.map.url,config:function(){return k.config&&k.config[a.map.id]||{}},exports:n[a.map.id]}}}; +X=function(a){this.events=W[a.id]||{};this.map=a;this.shim=k.shim[a.id];this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};X.prototype={init:function(a,d,b,l){l=l||{};if(!this.inited){this.factory=d;if(b)this.on("error",b);else this.events.error&&(b=s(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.depMaps.rjsSkipMap=a.rjsSkipMap;this.errback=b;this.inited=!0;this.ignore=l.ignore;l.enabled||this.enabled?this.enable():this.check()}},defineDepById:function(a, +d){var b;q(this.depMaps,function(d,f){if(d.id===a)return b=f,!0});return this.defineDep(b,d)},defineDep:function(a,d){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=d)},fetch:function(){if(!this.fetched){this.fetched=!0;h.startTime=(new Date).getTime();var a=this.map;if(this.shim)t(this,!0)(this.shim.deps||[],s(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=this.map.url;R[a]|| +(R[a]=!0,h.load(this.map.id,a))},check:function(a){if(this.enabled&&!this.enabling){var d=this.map.id,b=this.depExports,c=this.exports,f=this.factory,e;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){this.defining=!0;if(this.depCount<1&&!this.defined){if(x(f)){if(this.events.error)try{c=h.execCb(d,f,b,c)}catch(g){e=g}else c=h.execCb(d,f,b,c);if(this.map.isDefine)if((b=this.module)&&b.exports!==void 0&&b.exports!==this.exports)c=b.exports;else if(c===void 0&&this.usingExports)c= +this.exports;if(e)return e.requireMap=this.map,e.requireModules=[this.map.id],e.requireType="define",B(this.error=e)}else c=f;this.exports=c;if(this.map.isDefine&&!this.ignore&&(n[d]=c,j.onResourceLoad))j.onResourceLoad(h,this.map,this.depMaps);delete m[d];this.defined=!0;h.waitCount-=1;h.waitCount===0&&(M=[])}this.defining=!1;if(!a&&this.defined&&!this.defineEmitted)this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0}}else this.fetch()}},callPlugin:function(){var a= +this.map,d=a.id,b=g(a.prefix,null,!1,!0);p(b,"defined",s(this,function(b){var f=this.map.name,e=this.map.parentMap?this.map.parentMap.name:null;if(this.map.unnormalized){if(b.normalize&&(f=b.normalize(f,function(a){return c(a,e,!0)})||""),b=g(a.prefix+"!"+f,this.map.parentMap,!1,!0),p(b,"defined",s(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),b=m[b.id]){if(this.events.error)b.on("error",s(this,function(a){this.emit("error",a)}));b.enable()}}else f=s(this,function(a){this.init([], +function(){return a},null,{enabled:!0})}),f.error=s(this,function(a){this.inited=!0;this.error=a;a.requireModules=[d];y(m,function(a){a.map.id.indexOf(d+"_unnormalized")===0&&z(a.map.id)});B(a)}),f.fromText=function(a,d){var b=L;b&&(L=!1);r(g(a));j.exec(d);b&&(L=!0);h.completeLoad(a)},b.load(a.name,t(a.parentMap,!0,function(a,d){a.rjsSkipMap=!0;return h.require(a,d)}),f,k)}));h.enable(b,this);this.pluginMaps[b.id]=b},enable:function(){this.enabled=!0;if(!this.waitPushed)M.push(this),h.waitCount+= +1,this.waitPushed=!0;this.enabling=!0;q(this.depMaps,s(this,function(a,d){var b,c;if(typeof a==="string"){a=g(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.depMaps.rjsSkipMap);this.depMaps[d]=a;if(b=Q[a.id]){this.depExports[d]=b(this);return}this.depCount+=1;p(a,"defined",s(this,function(a){this.defineDep(d,a);this.check()}));this.errback&&p(a,"error",this.errback)}b=a.id;c=m[b];!Q[b]&&c&&!c.enabled&&h.enable(a,this)}));y(this.pluginMaps,s(this,function(a){var b=m[a.id];b&&!b.enabled&& +h.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){q(this.events[a],function(a){a(b)});a==="error"&&delete this.events[a]}};return h={config:k,contextName:b,registry:m,defined:n,urlFetched:R,waitCount:0,defQueue:F,Module:X,makeModuleMap:g,configure:function(a){a.baseUrl&&a.baseUrl.charAt(a.baseUrl.length-1)!=="/"&&(a.baseUrl+="/");var b=k.pkgs,c=k.shim,e=k.paths,f=k.map;K(k,a,!0);k.paths=K(e,a.paths,!0);if(a.map)k.map= +K(f||{},a.map,!0,!0);if(a.shim)y(a.shim,function(a,b){G(a)&&(a={deps:a});if(a.exports&&!a.exports.__buildReady)a.exports=h.makeShimExports(a.exports);c[b]=a}),k.shim=c;if(a.packages)q(a.packages,function(a){a=typeof a==="string"?{name:a}:a;b[a.name]={name:a.name,location:a.location||a.name,main:(a.main||"main").replace(ja,"").replace(ba,"")}}),k.pkgs=b;y(m,function(a,b){a.map=g(b)});if(a.deps||a.callback)h.require(a.deps||[],a.callback)},makeShimExports:function(a){var b;return typeof a==="string"? +(b=function(){return Z(a)},b.exports=a,b):function(){return a.apply(Y,arguments)}},requireDefined:function(a,b){var c=g(a,b,!1,!0).id;return n.hasOwnProperty(c)},requireSpecified:function(a,b){a=g(a,b,!1,!0).id;return n.hasOwnProperty(a)||m.hasOwnProperty(a)},require:function(a,d,c,e){var f;if(typeof a==="string"){if(x(d))return B(H("requireargs","Invalid require call"),c);if(j.get)return j.get(h,a,d);a=g(a,d,!1,!0);a=a.id;return!n.hasOwnProperty(a)?B(H("notloaded",'Module name "'+a+'" has not been loaded yet for context: '+ +b)):n[a]}c&&!x(c)&&(e=c,c=void 0);d&&!x(d)&&(e=d,d=void 0);for(u();F.length;)if(f=F.shift(),f[0]===null)return B(H("mismatch","Mismatched anonymous define() module: "+f[f.length-1]));else V(f);r(g(null,e)).init(a,d,c,{enabled:!0});E();return h.require},undef:function(a){var b=g(a,null,!0),c=m[a];delete n[a];delete R[b.url];delete W[a];if(c){if(c.events.defined)W[a]=c.events;z(a)}},enable:function(a){m[a.id]&&r(a).enable()},completeLoad:function(a){var b=k.shim[a]||{},c=b.exports&&b.exports.exports, +e,f;for(u();F.length;){f=F.shift();if(f[0]===null){f[0]=a;if(e)break;e=!0}else f[0]===a&&(e=!0);V(f)}f=m[a];if(!e&&!n[a]&&f&&!f.inited)if(k.enforceDefine&&(!c||!Z(c)))if(i(a))return;else return B(H("nodefine","No define call for "+a,null,[a]));else V([a,b.deps||[],b.exports]);E()},toUrl:function(a,b){var e=a.lastIndexOf("."),g=null;e!==-1&&(g=a.substring(e,a.length),a=a.substring(0,e));return h.nameToUrl(c(a,b&&b.id,!0),g)},nameToUrl:function(a,b){var c,e,f,g,h,i;if(j.jsExtRegExp.test(a))g=a+(b|| +"");else{c=k.paths;e=k.pkgs;g=a.split("/");for(h=g.length;h>0;h-=1)if(i=g.slice(0,h).join("/"),f=e[i],i=c[i]){G(i)&&(i=i[0]);g.splice(0,h,i);break}else if(f){c=a===f.name?f.location+"/"+f.main:f.location;g.splice(0,h,c);break}g=g.join("/")+(b||".js");g=(g.charAt(0)==="/"||g.match(/^[\w\+\.\-]+:/)?"":k.baseUrl)+g}return k.urlArgs?g+((g.indexOf("?")===-1?"?":"&")+k.urlArgs):g},load:function(a,b){j.load(h,a,b)},execCb:function(a,b,c,e){return b.apply(e,c)},onScriptLoad:function(a){if(a.type==="load"|| +la.test((a.currentTarget||a.srcElement).readyState))I=null,a=J(a),h.completeLoad(a.id)},onScriptError:function(a){var b=J(a);if(!i(b.id))return B(H("scripterror","Script error",a,[b.id]))}}}};j({});aa(j);if(w&&(t=A.head=document.getElementsByTagName("head")[0],C=document.getElementsByTagName("base")[0]))t=A.head=C.parentNode;j.onError=function(b){throw b;};j.load=function(b,c,e){var i=b&&b.config||{},g;if(w)return g=i.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script"), +g.type=i.scriptType||"text/javascript",g.charset="utf-8",g.async=!0,g.setAttribute("data-requirecontext",b.contextName),g.setAttribute("data-requiremodule",c),g.attachEvent&&!(g.attachEvent.toString&&g.attachEvent.toString().indexOf("[native code")<0)&&!S?(L=!0,g.attachEvent("onreadystatechange",b.onScriptLoad)):(g.addEventListener("load",b.onScriptLoad,!1),g.addEventListener("error",b.onScriptError,!1)),g.src=e,E=g,C?t.insertBefore(g,C):t.appendChild(g),E=null,g;else ca&&(importScripts(e),b.completeLoad(c))}; +w&&N(document.getElementsByTagName("script"),function(b){if(!t)t=b.parentNode;if(u=b.getAttribute("data-main")){if(!p.baseUrl)D=u.split("/"),da=D.pop(),ea=D.length?D.join("/")+"/":"./",p.baseUrl=ea,u=da;u=u.replace(ba,"");p.deps=p.deps?p.deps.concat(u):[u];return!0}});define=function(b,c,e){var i,g;typeof b!=="string"&&(e=c,c=b,b=null);G(c)||(e=c,c=[]);!c.length&&x(e)&&e.length&&(e.toString().replace(ha,"").replace(ia,function(b,e){c.push(e)}),c=(e.length===1?["require"]:["require","exports","module"]).concat(c)); +if(L&&(i=E||ga()))b||(b=i.getAttribute("data-requiremodule")),g=z[i.getAttribute("data-requirecontext")];(g?g.defQueue:P).push([b,c,e])};define.amd={jQuery:!0};j.exec=function(b){return eval(b)};j(p)}})(this); diff --git a/scripts/lib/esprima-master/assets/style.css b/scripts/lib/esprima-master/assets/style.css new file mode 100755 index 0000000..fcb7611 --- /dev/null +++ b/scripts/lib/esprima-master/assets/style.css @@ -0,0 +1,57 @@ +a:hover, a:active { + text-decoration: underline; +} + +.top-bar a, .tabs a { + text-decoration: none; +} + +div.row.copyright { + margin-top: 44px; + padding-top: 11px; + border-top: 1px solid #ddd; +} + +.code { + border-left: 3px solid #ddd; + margin: 5px 3px 8px 15px; + padding: 0 0 0 8px; +} + +.textviewContainer { + background-color: white; +} + +.textviewContainer, .contentassist { + font-family: 'Droid Sans Mono', Menlo, Consolas, 'Courier New', Courier, monospace, sans-serif; + font-size: 10pt; +} +.contentassist { + width: 400px; +} + +pre#editor { + border: 1px solid #ccc; +} + +div#info { + margin-top: 22px; +} + +.textviewTooltip { + color: black; + background-color: #ffffcc; + border-color: #aaa; +} + +.annotationRange.readOccurrence { + background-color: #ffffcc; + border: none; +} + +.annotationRange.writeOccurrence { + background-color: #ffffcc; + border: 1px solid #ffcc99; + margin: -1px; + border-radius: 4px; +} diff --git a/scripts/lib/esprima-master/bin/esparse.js b/scripts/lib/esprima-master/bin/esparse.js new file mode 100755 index 0000000..5603666 --- /dev/null +++ b/scripts/lib/esprima-master/bin/esparse.js @@ -0,0 +1,127 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2011 Ariya Hidayat + + 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 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 sloppy:true node:true rhino:true */ + +var fs, esprima, fname, content, options, syntax; + +if (typeof require === 'function') { + fs = require('fs'); + esprima = require('esprima'); +} else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esparse.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esparse [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --comment Gather all line and block comments in an array'); + console.log(' --loc Include line-column location info for each syntax node'); + console.log(' --range Include index-based range for each syntax node'); + console.log(' --raw Display the raw value of literals'); + console.log(' --tokens List all tokens in an array'); + console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); + console.log(' -v, --version Shows program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = {}; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry === '--comment') { + options.comment = true; + } else if (entry === '--loc') { + options.loc = true; + } else if (entry === '--range') { + options.range = true; + } else if (entry === '--raw') { + options.raw = true; + } else if (entry === '--tokens') { + options.tokens = true; + } else if (entry === '--tolerant') { + options.tolerant = true; + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else if (typeof fname === 'string') { + console.log('Error: more than one input file.'); + process.exit(1); + } else { + fname = entry; + } +}); + +if (typeof fname !== 'string') { + console.log('Error: no input file.'); + process.exit(1); +} + +// Special handling for regular expression literal since we need to +// convert it to a string literal, otherwise it will be decoded +// as object "{}" and the regular expression would be lost. +function adjustRegexLiteral(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return value; +} + +try { + content = fs.readFileSync(fname, 'utf-8'); + syntax = esprima.parse(content, options); + console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); +} catch (e) { + console.log('Error: ' + e.message); + process.exit(1); +} diff --git a/scripts/lib/esprima-master/bin/esvalidate.js b/scripts/lib/esprima-master/bin/esvalidate.js new file mode 100755 index 0000000..dddd8a2 --- /dev/null +++ b/scripts/lib/esprima-master/bin/esvalidate.js @@ -0,0 +1,199 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + + 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 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 sloppy:true plusplus:true node:true rhino:true */ +/*global phantom:true */ + +var fs, system, esprima, options, fnames, count; + +if (typeof esprima === 'undefined') { + // PhantomJS can only require() relative files + if (typeof phantom === 'object') { + fs = require('fs'); + system = require('system'); + esprima = require('./esprima'); + } else if (typeof require === 'function') { + fs = require('fs'); + esprima = require('esprima'); + } else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } + } +} + +// Shims to Node.js objects when running under PhantomJS 1.7+. +if (typeof phantom === 'object') { + fs.readFileSync = fs.read; + process = { + argv: [].slice.call(system.args), + exit: phantom.exit + }; + process.argv.unshift('phantomjs'); +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esvalidate.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esvalidate [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --format=type Set the report format, plain (default) or junit'); + console.log(' -v, --version Print program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = { + format: 'plain' +}; + +fnames = []; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry.slice(0, 9) === '--format=') { + options.format = entry.slice(9); + if (options.format !== 'plain' && options.format !== 'junit') { + console.log('Error: unknown report format ' + options.format + '.'); + process.exit(1); + } + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else { + fnames.push(entry); + } +}); + +if (fnames.length === 0) { + console.log('Error: no input file.'); + process.exit(1); +} + +if (options.format === 'junit') { + console.log(''); + console.log(''); +} + +count = 0; +fnames.forEach(function (fname) { + var content, timestamp, syntax, name; + try { + content = fs.readFileSync(fname, 'utf-8'); + + if (content[0] === '#' && content[1] === '!') { + content = '//' + content.substr(2, content.length); + } + + timestamp = Date.now(); + syntax = esprima.parse(content, { tolerant: true }); + + if (options.format === 'junit') { + + name = fname; + if (name.lastIndexOf('/') >= 0) { + name = name.slice(name.lastIndexOf('/') + 1); + } + + console.log(''); + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + console.log(' '); + console.log(' ' + + error.message + '(' + name + ':' + error.lineNumber + ')' + + ''); + console.log(' '); + }); + + console.log(''); + + } else if (options.format === 'plain') { + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + msg = fname + ':' + error.lineNumber + ': ' + msg; + console.log(msg); + ++count; + }); + + } + } catch (e) { + ++count; + if (options.format === 'junit') { + console.log(''); + console.log(' '); + console.log(' ' + + e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + + ')'); + console.log(' '); + console.log(''); + } else { + console.log('Error: ' + e.message); + } + } +}); + +if (options.format === 'junit') { + console.log(''); +} + +if (count > 0) { + process.exit(1); +} + +if (count === 0 && typeof phantom === 'object') { + process.exit(0); +} diff --git a/scripts/lib/esprima-master/bower.json b/scripts/lib/esprima-master/bower.json new file mode 100755 index 0000000..c61748a --- /dev/null +++ b/scripts/lib/esprima-master/bower.json @@ -0,0 +1,29 @@ +{ + "name": "esprima", + "version": "2.0.0-dev", + "main": "./esprima.js", + "scripts": [ + "esprima.js" + ], + "dependencies": {}, + "ignore": [ + "examples", + "test", + "tools" + ], + "repository": { + "type": "git", + "url": "http://github.com/ariya/esprima.git" + }, + "licenses": [{ + "type": "BSD", + "url": "http://github.com/ariya/esprima/raw/master/LICENSE.BSD" + }], + "keywords": [ + "ast", + "ecmascript", + "javascript", + "parser", + "syntax" + ] +} diff --git a/scripts/lib/esprima-master/component.json b/scripts/lib/esprima-master/component.json new file mode 100755 index 0000000..50ae14e --- /dev/null +++ b/scripts/lib/esprima-master/component.json @@ -0,0 +1,24 @@ +{ + "name": "esprima", + "version": "2.0.0-dev", + "main": "./esprima.js", + "scripts": [ + "esprima.js" + ], + "dependencies": {}, + "repository": { + "type": "git", + "url": "http://github.com/ariya/esprima.git" + }, + "licenses": [{ + "type": "BSD", + "url": "http://github.com/ariya/esprima/raw/master/LICENSE.BSD" + }], + "keywords": [ + "ast", + "ecmascript", + "javascript", + "parser", + "syntax" + ] +} diff --git a/scripts/lib/esprima-master/esprima.js b/scripts/lib/esprima-master/esprima.js new file mode 100755 index 0000000..7529302 --- /dev/null +++ b/scripts/lib/esprima-master/esprima.js @@ -0,0 +1,3974 @@ +/* + Copyright (C) 2013 Ariya Hidayat + Copyright (C) 2013 Thaddee Tyl + Copyright (C) 2013 Mathias Bynens + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Mathias Bynens + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Kris Kowal + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + + 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 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 plusplus:true */ +/*global esprima:true, define:true, exports:true, window: true, +throwErrorTolerant: true, +throwError: true, generateStatement: true, peek: true, +parseAssignmentExpression: true, parseBlock: true, parseExpression: true, +parseFunctionDeclaration: true, parseFunctionExpression: true, +parseFunctionSourceElements: true, parseVariableIdentifier: true, +parseLeftHandSideExpression: true, parseParams: true, validateParam: true, +parseUnaryExpression: true, +parseStatement: true, parseSourceElement: true */ + +(function (root, factory) { + 'use strict'; + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // Rhino, and plain browser loading. + + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory((root.esprima = {})); + } +}(this, function (exports) { + 'use strict'; + + var Token, + TokenName, + FnExprTokens, + Syntax, + PlaceHolders, + PropertyKind, + Messages, + Regex, + SyntaxTreeDelegate, + source, + strict, + index, + lineNumber, + lineStart, + length, + delegate, + lookahead, + state, + extra; + + Token = { + BooleanLiteral: 1, + EOF: 2, + Identifier: 3, + Keyword: 4, + NullLiteral: 5, + NumericLiteral: 6, + Punctuator: 7, + StringLiteral: 8, + RegularExpression: 9 + }; + + TokenName = {}; + TokenName[Token.BooleanLiteral] = 'Boolean'; + TokenName[Token.EOF] = ''; + TokenName[Token.Identifier] = 'Identifier'; + TokenName[Token.Keyword] = 'Keyword'; + TokenName[Token.NullLiteral] = 'Null'; + TokenName[Token.NumericLiteral] = 'Numeric'; + TokenName[Token.Punctuator] = 'Punctuator'; + TokenName[Token.StringLiteral] = 'String'; + TokenName[Token.RegularExpression] = 'RegularExpression'; + + // A function following one of those tokens is an expression. + FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', + 'return', 'case', 'delete', 'throw', 'void', + // assignment operators + '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', + '&=', '|=', '^=', ',', + // binary/unary operators + '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', + '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', + '<=', '<', '>', '!=', '!==']; + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + ArrowFunctionExpression: 'ArrowFunctionExpression', + 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' + }; + + PlaceHolders = { + ArrowParameterPlaceHolder: { + type: 'ArrowParameterPlaceHolder' + } + }; + + PropertyKind = { + Data: 1, + Get: 2, + Set: 4 + }; + + // Error messages should be identical to V8. + Messages = { + UnexpectedToken: 'Unexpected token %0', + UnexpectedNumber: 'Unexpected number', + UnexpectedString: 'Unexpected string', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedEOS: 'Unexpected end of input', + NewlineAfterThrow: 'Illegal newline after throw', + InvalidRegExp: 'Invalid regular expression', + UnterminatedRegExp: 'Invalid regular expression: missing /', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NoCatchOrFinally: 'Missing catch or finally after try', + UnknownLabel: 'Undefined label \'%0\'', + Redeclaration: '%0 \'%1\' has already been declared', + IllegalContinue: 'Illegal continue statement', + IllegalBreak: 'Illegal break statement', + IllegalReturn: 'Illegal return statement', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', + AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', + AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode' + }; + + // See also tools/generate-unicode-regex.py. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'), + NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]') + }; + + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + + function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + + function isDecimalDigit(ch) { + return (ch >= 48 && ch <= 57); // 0..9 + } + + function isHexDigit(ch) { + return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; + } + + function isOctalDigit(ch) { + return '01234567'.indexOf(ch) >= 0; + } + + + // 7.2 White Space + + function isWhiteSpace(ch) { + return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || + (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); + } + + // 7.6 Identifier Names and Identifiers + + function isIdentifierStart(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); + } + + function isIdentifierPart(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch >= 0x30 && ch <= 0x39) || // 0..9 + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); + } + + // 7.6.1.2 Future Reserved Words + + function isFutureReservedWord(id) { + switch (id) { + case 'class': + case 'enum': + case 'export': + case 'extends': + case 'import': + case 'super': + return true; + default: + return false; + } + } + + function isStrictModeReservedWord(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'yield': + case 'let': + return true; + default: + return false; + } + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + // 7.6.1.1 Keywords + + function isKeyword(id) { + if (strict && isStrictModeReservedWord(id)) { + return true; + } + + // 'const' is specialized as Keyword in V8. + // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next. + // Some others are from future reserved words. + + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || + (id === 'try') || (id === 'let'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + } + + // 7.4 Comments + + function addComment(type, value, start, end, loc) { + var comment, attacher; + + assert(typeof start === 'number', 'Comment must have valid position'); + + // Because the way the actual token is scanned, often the comments + // (if any) are skipped twice during the lexical analysis. + // Thus, we need to skip adding a comment if the comment array already + // handled it. + if (state.lastCommentStart >= start) { + return; + } + state.lastCommentStart = start; + + comment = { + type: type, + value: value + }; + if (extra.range) { + comment.range = [start, end]; + } + if (extra.loc) { + comment.loc = loc; + } + extra.comments.push(comment); + if (extra.attachComment) { + extra.leadingComments.push(comment); + extra.trailingComments.push(comment); + } + } + + function skipSingleLineComment(offset) { + var start, loc, ch, comment; + + start = index - offset; + loc = { + start: { + line: lineNumber, + column: index - lineStart - offset + } + }; + + while (index < length) { + ch = source.charCodeAt(index); + ++index; + if (isLineTerminator(ch)) { + if (extra.comments) { + comment = source.slice(start + offset, index - 1); + loc.end = { + line: lineNumber, + column: index - lineStart - 1 + }; + addComment('Line', comment, start, index - 1, loc); + } + if (ch === 13 && source.charCodeAt(index) === 10) { + ++index; + } + ++lineNumber; + lineStart = index; + return; + } + } + + if (extra.comments) { + comment = source.slice(start + offset, index); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Line', comment, start, index, loc); + } + } + + function skipMultiLineComment() { + var start, loc, ch, comment; + + if (extra.comments) { + start = index - 2; + loc = { + start: { + line: lineNumber, + column: index - lineStart - 2 + } + }; + } + + while (index < length) { + ch = source.charCodeAt(index); + if (isLineTerminator(ch)) { + if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) { + ++index; + } + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } else if (ch === 0x2A) { + // Block comment ends with '*/'. + if (source.charCodeAt(index + 1) === 0x2F) { + ++index; + ++index; + if (extra.comments) { + comment = source.slice(start + 2, index - 2); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Block', comment, start, index, loc); + } + return; + } + ++index; + } else { + ++index; + } + } + + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + function skipComment() { + var ch, start; + + start = (index === 0); + while (index < length) { + ch = source.charCodeAt(index); + + if (isWhiteSpace(ch)) { + ++index; + } else if (isLineTerminator(ch)) { + ++index; + if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { + ++index; + } + ++lineNumber; + lineStart = index; + start = true; + } else if (ch === 0x2F) { // U+002F is '/' + ch = source.charCodeAt(index + 1); + if (ch === 0x2F) { + ++index; + ++index; + skipSingleLineComment(2); + start = true; + } else if (ch === 0x2A) { // U+002A is '*' + ++index; + ++index; + skipMultiLineComment(); + } else { + break; + } + } else if (start && ch === 0x2D) { // U+002D is '-' + // U+003E is '>' + if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) { + // '-->' is a single-line comment + index += 3; + skipSingleLineComment(3); + } else { + break; + } + } else if (ch === 0x3C) { // U+003C is '<' + if (source.slice(index + 1, index + 4) === '!--') { + ++index; // `<` + ++index; // `!` + ++index; // `-` + ++index; // `-` + skipSingleLineComment(4); + } else { + break; + } + } else { + break; + } + } + } + + function scanHexEscape(prefix) { + var i, len, ch, code = 0; + + len = (prefix === 'u') ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && isHexDigit(source[index])) { + ch = source[index++]; + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } + + function scanUnicodeCodePointEscape() { + var ch, code, cu1, cu2; + + ch = source[index]; + code = 0; + + // At least, one hex digit is required. + if (ch === '}') { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + while (index < length) { + ch = source[index++]; + if (!isHexDigit(ch)) { + break; + } + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } + + if (code > 0x10FFFF || ch !== '}') { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + // UTF-16 Encoding + if (code <= 0xFFFF) { + return String.fromCharCode(code); + } + cu1 = ((code - 0x10000) >> 10) + 0xD800; + cu2 = ((code - 0x10000) & 1023) + 0xDC00; + return String.fromCharCode(cu1, cu2); + } + + function getEscapedIdentifier() { + var ch, id; + + ch = source.charCodeAt(index++); + id = String.fromCharCode(ch); + + // '\u' (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + if (source.charCodeAt(index) !== 0x75) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + ++index; + ch = scanHexEscape('u'); + if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + id = ch; + } + + while (index < length) { + ch = source.charCodeAt(index); + if (!isIdentifierPart(ch)) { + break; + } + ++index; + id += String.fromCharCode(ch); + + // '\u' (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + id = id.substr(0, id.length - 1); + if (source.charCodeAt(index) !== 0x75) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + ++index; + ch = scanHexEscape('u'); + if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + id += ch; + } + } + + return id; + } + + function getIdentifier() { + var start, ch; + + start = index++; + while (index < length) { + ch = source.charCodeAt(index); + if (ch === 0x5C) { + // Blackslash (U+005C) marks Unicode escape sequence. + index = start; + return getEscapedIdentifier(); + } + if (isIdentifierPart(ch)) { + ++index; + } else { + break; + } + } + + return source.slice(start, index); + } + + function scanIdentifier() { + var start, id, type; + + start = index; + + // Backslash (U+005C) starts an escaped character. + id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); + + // There is no keyword or literal with only one character. + // Thus, it must be an identifier. + if (id.length === 1) { + type = Token.Identifier; + } else if (isKeyword(id)) { + // A keyword can not contained escaped characters. + if (index - start === id.length) { + type = Token.Keyword; + } else { + type = Token.Identifier; + } + } else if (id === 'null') { + type = Token.NullLiteral; + } else if (id === 'true' || id === 'false') { + type = Token.BooleanLiteral; + } else { + type = Token.Identifier; + } + + return { + type: type, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + + // 7.7 Punctuators + + function scanPunctuator() { + var start = index, + code = source.charCodeAt(index), + code2, + ch1 = source[index], + ch2, + ch3, + ch4; + + switch (code) { + + // Check for most common single-character punctuators. + case 0x2E: // . dot + case 0x28: // ( open bracket + case 0x29: // ) close bracket + case 0x3B: // ; semicolon + case 0x2C: // , comma + case 0x7B: // { open curly brace + case 0x7D: // } close curly brace + case 0x5B: // [ + case 0x5D: // ] + case 0x3A: // : + case 0x3F: // ? + case 0x7E: // ~ + ++index; + if (extra.tokenize) { + if (code === 0x28) { + extra.openParenToken = extra.tokens.length; + } else if (code === 0x7B) { + extra.openCurlyToken = extra.tokens.length; + } + } + return { + type: Token.Punctuator, + value: String.fromCharCode(code), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + + default: + code2 = source.charCodeAt(index + 1); + + // '=' (U+003D) marks an assignment or comparison operator. + if (code2 === 0x3D) { + switch (code) { + case 0x2B: // + + case 0x2D: // - + case 0x2F: // / + case 0x3C: // < + case 0x3E: // > + case 0x5E: // ^ + case 0x7C: // | + case 0x25: // % + case 0x26: // & + case 0x2A: // * + index += 2; + return { + type: Token.Punctuator, + value: String.fromCharCode(code) + String.fromCharCode(code2), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + + case 0x21: // ! + case 0x3D: // = + index += 2; + + // !== and === + if (source.charCodeAt(index) === 0x3D) { + ++index; + } + return { + type: Token.Punctuator, + value: source.slice(start, index), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + } + break; + } + + // Peek more characters. + + ch2 = source[index + 1]; + ch3 = source[index + 2]; + ch4 = source[index + 3]; + + // 4-character punctuator: >>>= + + if (ch1 === '>' && ch2 === '>' && ch3 === '>') { + if (ch4 === '=') { + index += 4; + return { + type: Token.Punctuator, + value: '>>>=', + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + } + + // 3-character punctuators: === !== >>> <<= >>= + + if (ch1 === '>' && ch2 === '>' && ch3 === '>') { + index += 3; + return { + type: Token.Punctuator, + value: '>>>', + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + if (ch1 === '<' && ch2 === '<' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '<<=', + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + if (ch1 === '>' && ch2 === '>' && ch3 === '=') { + index += 3; + return { + type: Token.Punctuator, + value: '>>=', + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + // Other 2-character punctuators: ++ -- << >> && || + + if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) { + index += 2; + return { + type: Token.Punctuator, + value: ch1 + ch2, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + if (ch1 === '=' && ch2 === '>') { + index += 2; + return { + type: Token.Punctuator, + value: '=>', + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + // 7.8.3 Numeric Literals + + function scanHexLiteral(start) { + var number = ''; + + while (index < length) { + if (!isHexDigit(source[index])) { + break; + } + number += source[index++]; + } + + if (number.length === 0) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + if (isIdentifierStart(source.charCodeAt(index))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.NumericLiteral, + value: parseInt('0x' + number, 16), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function scanOctalLiteral(start) { + var number = '0' + source[index++]; + while (index < length) { + if (!isOctalDigit(source[index])) { + break; + } + number += source[index++]; + } + + if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.NumericLiteral, + value: parseInt(number, 8), + octal: true, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function scanNumericLiteral() { + var number, start, ch; + + ch = source[index]; + assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), + 'Numeric literal must start with a decimal digit or a decimal point'); + + start = index; + number = ''; + if (ch !== '.') { + number = source[index++]; + ch = source[index]; + + // Hex number starts with '0x'. + // Octal number starts with '0'. + if (number === '0') { + if (ch === 'x' || ch === 'X') { + ++index; + return scanHexLiteral(start); + } + if (isOctalDigit(ch)) { + return scanOctalLiteral(start); + } + + // decimal number starts with '0' such as '09' is illegal. + if (ch && isDecimalDigit(ch.charCodeAt(0))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + while (isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + ch = source[index]; + } + + if (ch === '.') { + number += source[index++]; + while (isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + ch = source[index]; + } + + if (ch === 'e' || ch === 'E') { + number += source[index++]; + + ch = source[index]; + if (ch === '+' || ch === '-') { + number += source[index++]; + } + if (isDecimalDigit(source.charCodeAt(index))) { + while (isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + } else { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + } + + if (isIdentifierStart(source.charCodeAt(index))) { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.NumericLiteral, + value: parseFloat(number), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + // 7.8.4 String Literals + + function scanStringLiteral() { + var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart; + startLineNumber = lineNumber; + startLineStart = lineStart; + + quote = source[index]; + assert((quote === '\'' || quote === '"'), + 'String literal must starts with a quote'); + + start = index; + ++index; + + while (index < length) { + ch = source[index++]; + + if (ch === quote) { + quote = ''; + break; + } else if (ch === '\\') { + ch = source[index++]; + if (!ch || !isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'u': + case 'x': + if (source[index] === '{') { + ++index; + str += scanUnicodeCodePointEscape(); + } else { + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + str += unescaped; + } else { + index = restore; + str += ch; + } + } + break; + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\x0B'; + break; + + default: + if (isOctalDigit(ch)) { + code = '01234567'.indexOf(ch); + + // \0 is not octal escape sequence + if (code !== 0) { + octal = true; + } + + if (index < length && isOctalDigit(source[index])) { + octal = true; + code = code * 8 + '01234567'.indexOf(source[index++]); + + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && + index < length && + isOctalDigit(source[index])) { + code = code * 8 + '01234567'.indexOf(source[index++]); + } + } + str += String.fromCharCode(code); + } else { + str += ch; + } + break; + } + } else { + ++lineNumber; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + lineStart = index; + } + } else if (isLineTerminator(ch.charCodeAt(0))) { + break; + } else { + str += ch; + } + } + + if (quote !== '') { + throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); + } + + return { + type: Token.StringLiteral, + value: str, + octal: octal, + startLineNumber: startLineNumber, + startLineStart: startLineStart, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function testRegExp(pattern, flags) { + var value; + try { + value = new RegExp(pattern, flags); + } catch (e) { + throwError({}, Messages.InvalidRegExp); + } + return value; + } + + function scanRegExpBody() { + var ch, str, classMarker, terminated, body; + + ch = source[index]; + assert(ch === '/', 'Regular expression literal must start with a slash'); + str = source[index++]; + + classMarker = false; + terminated = false; + while (index < length) { + ch = source[index++]; + str += ch; + if (ch === '\\') { + ch = source[index++]; + // ECMA-262 7.8.5 + if (isLineTerminator(ch.charCodeAt(0))) { + throwError({}, Messages.UnterminatedRegExp); + } + str += ch; + } else if (isLineTerminator(ch.charCodeAt(0))) { + throwError({}, Messages.UnterminatedRegExp); + } else if (classMarker) { + if (ch === ']') { + classMarker = false; + } + } else { + if (ch === '/') { + terminated = true; + break; + } else if (ch === '[') { + classMarker = true; + } + } + } + + if (!terminated) { + throwError({}, Messages.UnterminatedRegExp); + } + + // Exclude leading and trailing slash. + body = str.substr(1, str.length - 2); + return { + value: body, + literal: str + }; + } + + function scanRegExpFlags() { + var ch, str, flags, restore; + + str = ''; + flags = ''; + while (index < length) { + ch = source[index]; + if (!isIdentifierPart(ch.charCodeAt(0))) { + break; + } + + ++index; + if (ch === '\\' && index < length) { + ch = source[index]; + if (ch === 'u') { + ++index; + restore = index; + ch = scanHexEscape('u'); + if (ch) { + flags += ch; + for (str += '\\u'; restore < index; ++restore) { + str += source[restore]; + } + } else { + index = restore; + flags += 'u'; + str += '\\u'; + } + throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); + } else { + str += '\\'; + } + } else { + flags += ch; + str += ch; + } + } + + return { + value: flags, + literal: str + }; + } + + function scanRegExp() { + var start, body, flags, pattern, value; + + lookahead = null; + skipComment(); + start = index; + + body = scanRegExpBody(); + flags = scanRegExpFlags(); + value = testRegExp(body.value, flags.value); + + if (extra.tokenize) { + return { + type: Token.RegularExpression, + value: value, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + return { + literal: body.literal + flags.literal, + value: value, + start: start, + end: index + }; + } + + function collectRegex() { + var pos, loc, regex, token; + + skipComment(); + + pos = index; + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + regex = scanRegExp(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + /* istanbul ignore next */ + if (!extra.tokenize) { + // Pop the previous token, which is likely '/' or '/=' + if (extra.tokens.length > 0) { + token = extra.tokens[extra.tokens.length - 1]; + if (token.range[0] === pos && token.type === 'Punctuator') { + if (token.value === '/' || token.value === '/=') { + extra.tokens.pop(); + } + } + } + + extra.tokens.push({ + type: 'RegularExpression', + value: regex.literal, + range: [pos, index], + loc: loc + }); + } + + return regex; + } + + function isIdentifierName(token) { + return token.type === Token.Identifier || + token.type === Token.Keyword || + token.type === Token.BooleanLiteral || + token.type === Token.NullLiteral; + } + + function advanceSlash() { + var prevToken, + checkToken; + // Using the following algorithm: + // https://github.com/mozilla/sweet.js/wiki/design + prevToken = extra.tokens[extra.tokens.length - 1]; + if (!prevToken) { + // Nothing before that: it cannot be a division. + return collectRegex(); + } + if (prevToken.type === 'Punctuator') { + if (prevToken.value === ']') { + return scanPunctuator(); + } + if (prevToken.value === ')') { + checkToken = extra.tokens[extra.openParenToken - 1]; + if (checkToken && + checkToken.type === 'Keyword' && + (checkToken.value === 'if' || + checkToken.value === 'while' || + checkToken.value === 'for' || + checkToken.value === 'with')) { + return collectRegex(); + } + return scanPunctuator(); + } + if (prevToken.value === '}') { + // Dividing a function by anything makes little sense, + // but we have to check for that. + if (extra.tokens[extra.openCurlyToken - 3] && + extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { + // Anonymous function. + checkToken = extra.tokens[extra.openCurlyToken - 4]; + if (!checkToken) { + return scanPunctuator(); + } + } else if (extra.tokens[extra.openCurlyToken - 4] && + extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { + // Named function. + checkToken = extra.tokens[extra.openCurlyToken - 5]; + if (!checkToken) { + return collectRegex(); + } + } else { + return scanPunctuator(); + } + // checkToken determines whether the function is + // a declaration or an expression. + if (FnExprTokens.indexOf(checkToken.value) >= 0) { + // It is an expression. + return scanPunctuator(); + } + // It is a declaration. + return collectRegex(); + } + return collectRegex(); + } + if (prevToken.type === 'Keyword') { + return collectRegex(); + } + return scanPunctuator(); + } + + function advance() { + var ch; + + skipComment(); + + if (index >= length) { + return { + type: Token.EOF, + lineNumber: lineNumber, + lineStart: lineStart, + start: index, + end: index + }; + } + + ch = source.charCodeAt(index); + + if (isIdentifierStart(ch)) { + return scanIdentifier(); + } + + // Very common: ( and ) and ; + if (ch === 0x28 || ch === 0x29 || ch === 0x3A) { + return scanPunctuator(); + } + + // String literal starts with single quote (U+0027) or double quote (U+0022). + if (ch === 0x27 || ch === 0x22) { + return scanStringLiteral(); + } + + + // Dot (.) U+002E can also start a floating-point number, hence the need + // to check the next character. + if (ch === 0x2E) { + if (isDecimalDigit(source.charCodeAt(index + 1))) { + return scanNumericLiteral(); + } + return scanPunctuator(); + } + + if (isDecimalDigit(ch)) { + return scanNumericLiteral(); + } + + // Slash (/) U+002F can also start a regex. + if (extra.tokenize && ch === 0x2F) { + return advanceSlash(); + } + + return scanPunctuator(); + } + + function collectToken() { + var loc, token, range, value; + + skipComment(); + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + token = advance(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + if (token.type !== Token.EOF) { + value = source.slice(token.start, token.end); + extra.tokens.push({ + type: TokenName[token.type], + value: value, + range: [token.start, token.end], + loc: loc + }); + } + + return token; + } + + function lex() { + var token; + + token = lookahead; + index = token.end; + lineNumber = token.lineNumber; + lineStart = token.lineStart; + + lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); + + index = token.end; + lineNumber = token.lineNumber; + lineStart = token.lineStart; + + return token; + } + + function peek() { + var pos, line, start; + + pos = index; + line = lineNumber; + start = lineStart; + lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); + index = pos; + lineNumber = line; + lineStart = start; + } + + function Position(line, column) { + this.line = line; + this.column = column; + } + + function SourceLocation(startLine, startColumn, line, column) { + this.start = new Position(startLine, startColumn); + this.end = new Position(line, column); + } + + SyntaxTreeDelegate = { + + name: 'SyntaxTree', + + processComment: function (node) { + var lastChild, trailingComments; + if (typeof node.type === 'undefined' || node.type === Syntax.Program) { + return; + } + + peek(); + + if (extra.trailingComments.length > 0) { + if (extra.trailingComments[0].range[0] >= node.range[1]) { + trailingComments = extra.trailingComments; + extra.trailingComments = []; + } else { + extra.trailingComments.length = 0; + } + } else { + if (extra.bottomRightStack.length > 0 && + extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments && + extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) { + trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; + delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; + } + } + + // Eating the stack. + while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) { + lastChild = extra.bottomRightStack.pop(); + } + + if (lastChild) { + if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { + node.leadingComments = lastChild.leadingComments; + delete lastChild.leadingComments; + } + } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { + node.leadingComments = extra.leadingComments; + extra.leadingComments = []; + } + + + if (trailingComments) { + node.trailingComments = trailingComments; + } + + extra.bottomRightStack.push(node); + }, + + markEnd: function (node, startToken) { + if (extra.range) { + node.range = [startToken.start, index]; + } + if (extra.loc) { + node.loc = new SourceLocation( + startToken.startLineNumber === undefined ? startToken.lineNumber : startToken.startLineNumber, + startToken.start - (startToken.startLineStart === undefined ? startToken.lineStart : startToken.startLineStart), + lineNumber, + index - lineStart + ); + this.postProcess(node); + } + + if (extra.attachComment) { + this.processComment(node); + } + return node; + }, + + postProcess: function (node) { + if (extra.source) { + node.loc.source = extra.source; + } + return node; + }, + + createArrayExpression: function (elements) { + return { + type: Syntax.ArrayExpression, + elements: elements + }; + }, + + createArrowFunctionExpression: function (params, body, expression) { + return { + type: Syntax.ArrowFunctionExpression, + id: null, + params: params, + defaults: [], + body: body, + rest: null, + generator: false, + expression: expression + }; + }, + + createAssignmentExpression: function (operator, left, right) { + return { + type: Syntax.AssignmentExpression, + operator: operator, + left: left, + right: right + }; + }, + + createBinaryExpression: function (operator, left, right) { + var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : + Syntax.BinaryExpression; + return { + type: type, + operator: operator, + left: left, + right: right + }; + }, + + createBlockStatement: function (body) { + return { + type: Syntax.BlockStatement, + body: body + }; + }, + + createBreakStatement: function (label) { + return { + type: Syntax.BreakStatement, + label: label + }; + }, + + createCallExpression: function (callee, args) { + return { + type: Syntax.CallExpression, + callee: callee, + 'arguments': args + }; + }, + + createCatchClause: function (param, body) { + return { + type: Syntax.CatchClause, + param: param, + body: body + }; + }, + + createConditionalExpression: function (test, consequent, alternate) { + return { + type: Syntax.ConditionalExpression, + test: test, + consequent: consequent, + alternate: alternate + }; + }, + + createContinueStatement: function (label) { + return { + type: Syntax.ContinueStatement, + label: label + }; + }, + + createDebuggerStatement: function () { + return { + type: Syntax.DebuggerStatement + }; + }, + + createDoWhileStatement: function (body, test) { + return { + type: Syntax.DoWhileStatement, + body: body, + test: test + }; + }, + + createEmptyStatement: function () { + return { + type: Syntax.EmptyStatement + }; + }, + + createExpressionStatement: function (expression) { + return { + type: Syntax.ExpressionStatement, + expression: expression + }; + }, + + createForStatement: function (init, test, update, body) { + return { + type: Syntax.ForStatement, + init: init, + test: test, + update: update, + body: body + }; + }, + + createForInStatement: function (left, right, body) { + return { + type: Syntax.ForInStatement, + left: left, + right: right, + body: body, + each: false + }; + }, + + createFunctionDeclaration: function (id, params, defaults, body) { + return { + type: Syntax.FunctionDeclaration, + id: id, + params: params, + defaults: defaults, + body: body, + rest: null, + generator: false, + expression: false + }; + }, + + createFunctionExpression: function (id, params, defaults, body) { + return { + type: Syntax.FunctionExpression, + id: id, + params: params, + defaults: defaults, + body: body, + rest: null, + generator: false, + expression: false + }; + }, + + createIdentifier: function (name) { + return { + type: Syntax.Identifier, + name: name + }; + }, + + createIfStatement: function (test, consequent, alternate) { + return { + type: Syntax.IfStatement, + test: test, + consequent: consequent, + alternate: alternate + }; + }, + + createLabeledStatement: function (label, body) { + return { + type: Syntax.LabeledStatement, + label: label, + body: body + }; + }, + + createLiteral: function (token) { + return { + type: Syntax.Literal, + value: token.value, + raw: source.slice(token.start, token.end) + }; + }, + + createMemberExpression: function (accessor, object, property) { + return { + type: Syntax.MemberExpression, + computed: accessor === '[', + object: object, + property: property + }; + }, + + createNewExpression: function (callee, args) { + return { + type: Syntax.NewExpression, + callee: callee, + 'arguments': args + }; + }, + + createObjectExpression: function (properties) { + return { + type: Syntax.ObjectExpression, + properties: properties + }; + }, + + createPostfixExpression: function (operator, argument) { + return { + type: Syntax.UpdateExpression, + operator: operator, + argument: argument, + prefix: false + }; + }, + + createProgram: function (body) { + return { + type: Syntax.Program, + body: body + }; + }, + + createProperty: function (kind, key, value) { + return { + type: Syntax.Property, + key: key, + value: value, + kind: kind + }; + }, + + createReturnStatement: function (argument) { + return { + type: Syntax.ReturnStatement, + argument: argument + }; + }, + + createSequenceExpression: function (expressions) { + return { + type: Syntax.SequenceExpression, + expressions: expressions + }; + }, + + createSwitchCase: function (test, consequent) { + return { + type: Syntax.SwitchCase, + test: test, + consequent: consequent + }; + }, + + createSwitchStatement: function (discriminant, cases) { + return { + type: Syntax.SwitchStatement, + discriminant: discriminant, + cases: cases + }; + }, + + createThisExpression: function () { + return { + type: Syntax.ThisExpression + }; + }, + + createThrowStatement: function (argument) { + return { + type: Syntax.ThrowStatement, + argument: argument + }; + }, + + createTryStatement: function (block, guardedHandlers, handlers, finalizer) { + return { + type: Syntax.TryStatement, + block: block, + guardedHandlers: guardedHandlers, + handlers: handlers, + finalizer: finalizer + }; + }, + + createUnaryExpression: function (operator, argument) { + if (operator === '++' || operator === '--') { + return { + type: Syntax.UpdateExpression, + operator: operator, + argument: argument, + prefix: true + }; + } + return { + type: Syntax.UnaryExpression, + operator: operator, + argument: argument, + prefix: true + }; + }, + + createVariableDeclaration: function (declarations, kind) { + return { + type: Syntax.VariableDeclaration, + declarations: declarations, + kind: kind + }; + }, + + createVariableDeclarator: function (id, init) { + return { + type: Syntax.VariableDeclarator, + id: id, + init: init + }; + }, + + createWhileStatement: function (test, body) { + return { + type: Syntax.WhileStatement, + test: test, + body: body + }; + }, + + createWithStatement: function (object, body) { + return { + type: Syntax.WithStatement, + object: object, + body: body + }; + } + }; + + // Return true if there is a line terminator before the next token. + + function peekLineTerminator() { + var pos, line, start, found; + + pos = index; + line = lineNumber; + start = lineStart; + skipComment(); + found = lineNumber !== line; + index = pos; + lineNumber = line; + lineStart = start; + + return found; + } + + // Throw an exception + + function throwError(token, messageFormat) { + var error, + args = Array.prototype.slice.call(arguments, 2), + msg = messageFormat.replace( + /%(\d)/g, + function (whole, index) { + assert(index < args.length, 'Message reference must be in range'); + return args[index]; + } + ); + + if (typeof token.lineNumber === 'number') { + error = new Error('Line ' + token.lineNumber + ': ' + msg); + error.index = token.start; + error.lineNumber = token.lineNumber; + error.column = token.start - lineStart + 1; + } else { + error = new Error('Line ' + lineNumber + ': ' + msg); + error.index = index; + error.lineNumber = lineNumber; + error.column = index - lineStart + 1; + } + + error.description = msg; + throw error; + } + + function throwErrorTolerant() { + try { + throwError.apply(null, arguments); + } catch (e) { + if (extra.errors) { + extra.errors.push(e); + } else { + throw e; + } + } + } + + + // Throw an exception because of the token. + + function throwUnexpected(token) { + if (token.type === Token.EOF) { + throwError(token, Messages.UnexpectedEOS); + } + + if (token.type === Token.NumericLiteral) { + throwError(token, Messages.UnexpectedNumber); + } + + if (token.type === Token.StringLiteral) { + throwError(token, Messages.UnexpectedString); + } + + if (token.type === Token.Identifier) { + throwError(token, Messages.UnexpectedIdentifier); + } + + if (token.type === Token.Keyword) { + if (isFutureReservedWord(token.value)) { + throwError(token, Messages.UnexpectedReserved); + } else if (strict && isStrictModeReservedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictReservedWord); + return; + } + throwError(token, Messages.UnexpectedToken, token.value); + } + + // BooleanLiteral, NullLiteral, or Punctuator. + throwError(token, Messages.UnexpectedToken, token.value); + } + + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + + function expect(value) { + var token = lex(); + if (token.type !== Token.Punctuator || token.value !== value) { + throwUnexpected(token); + } + } + + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + + function expectKeyword(keyword) { + var token = lex(); + if (token.type !== Token.Keyword || token.value !== keyword) { + throwUnexpected(token); + } + } + + // Return true if the next token matches the specified punctuator. + + function match(value) { + return lookahead.type === Token.Punctuator && lookahead.value === value; + } + + // Return true if the next token matches the specified keyword + + function matchKeyword(keyword) { + return lookahead.type === Token.Keyword && lookahead.value === keyword; + } + + // Return true if the next token is an assignment operator + + function matchAssign() { + var op; + + if (lookahead.type !== Token.Punctuator) { + return false; + } + op = lookahead.value; + return op === '=' || + op === '*=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + } + + function consumeSemicolon() { + var line; + + // Catch the very common case first: immediately a semicolon (U+003B). + if (source.charCodeAt(index) === 0x3B) { + lex(); + return; + } + + line = lineNumber; + skipComment(); + if (lineNumber !== line) { + return; + } + + if (match(';')) { + lex(); + return; + } + + if (lookahead.type !== Token.EOF && !match('}')) { + throwUnexpected(lookahead); + } + } + + // Return true if provided expression is LeftHandSideExpression + + function isLeftHandSide(expr) { + return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; + } + + // 11.1.4 Array Initialiser + + function parseArrayInitialiser() { + var elements = [], startToken; + + startToken = lookahead; + expect('['); + + while (!match(']')) { + if (match(',')) { + lex(); + elements.push(null); + } else { + elements.push(parseAssignmentExpression()); + + if (!match(']')) { + expect(','); + } + } + } + + lex(); + + return delegate.markEnd(delegate.createArrayExpression(elements), startToken); + } + + // 11.1.5 Object Initialiser + + function parsePropertyFunction(param, first) { + var previousStrict, body, startToken; + + previousStrict = strict; + startToken = lookahead; + body = parseFunctionSourceElements(); + if (first && strict && isRestrictedWord(param[0].name)) { + throwErrorTolerant(first, Messages.StrictParamName); + } + strict = previousStrict; + return delegate.markEnd(delegate.createFunctionExpression(null, param, [], body), startToken); + } + + function parseObjectPropertyKey() { + var token, startToken; + + startToken = lookahead; + token = lex(); + + // Note: This function is called only from parseObjectProperty(), where + // EOF and Punctuator tokens are already filtered out. + + if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { + if (strict && token.octal) { + throwErrorTolerant(token, Messages.StrictOctalLiteral); + } + return delegate.markEnd(delegate.createLiteral(token), startToken); + } + + return delegate.markEnd(delegate.createIdentifier(token.value), startToken); + } + + function parseObjectProperty() { + var token, key, id, value, param, startToken; + + token = lookahead; + startToken = lookahead; + + if (token.type === Token.Identifier) { + + id = parseObjectPropertyKey(); + + // Property Assignment: Getter and Setter. + + if (token.value === 'get' && !match(':')) { + key = parseObjectPropertyKey(); + expect('('); + expect(')'); + value = parsePropertyFunction([]); + return delegate.markEnd(delegate.createProperty('get', key, value), startToken); + } + if (token.value === 'set' && !match(':')) { + key = parseObjectPropertyKey(); + expect('('); + token = lookahead; + if (token.type !== Token.Identifier) { + expect(')'); + throwErrorTolerant(token, Messages.UnexpectedToken, token.value); + value = parsePropertyFunction([]); + } else { + param = [ parseVariableIdentifier() ]; + expect(')'); + value = parsePropertyFunction(param, token); + } + return delegate.markEnd(delegate.createProperty('set', key, value), startToken); + } + expect(':'); + value = parseAssignmentExpression(); + return delegate.markEnd(delegate.createProperty('init', id, value), startToken); + } + if (token.type === Token.EOF || token.type === Token.Punctuator) { + throwUnexpected(token); + } else { + key = parseObjectPropertyKey(); + expect(':'); + value = parseAssignmentExpression(); + return delegate.markEnd(delegate.createProperty('init', key, value), startToken); + } + } + + function parseObjectInitialiser() { + var properties = [], property, name, key, kind, map = {}, toString = String, startToken; + + startToken = lookahead; + + expect('{'); + + while (!match('}')) { + property = parseObjectProperty(); + + if (property.key.type === Syntax.Identifier) { + name = property.key.name; + } else { + name = toString(property.key.value); + } + kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; + + key = '$' + name; + if (Object.prototype.hasOwnProperty.call(map, key)) { + if (map[key] === PropertyKind.Data) { + if (strict && kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.StrictDuplicateProperty); + } else if (kind !== PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } + } else { + if (kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } else if (map[key] & kind) { + throwErrorTolerant({}, Messages.AccessorGetSet); + } + } + map[key] |= kind; + } else { + map[key] = kind; + } + + properties.push(property); + + if (!match('}')) { + expect(','); + } + } + + expect('}'); + + return delegate.markEnd(delegate.createObjectExpression(properties), startToken); + } + + // 11.1.6 The Grouping Operator + + function parseGroupExpression() { + var expr, params, startToken = lookahead; + + expect('('); + + if (match(')')) { + lex(); + return PlaceHolders.ArrowParameterPlaceHolder; + } + + ++state.parenthesisCount; + + expr = parseExpression(); + + expect(')'); + + return expr; + } + + + // 11.1 Primary Expressions + + function parsePrimaryExpression() { + var type, token, expr, startToken; + + if (match('(')) { + return parseGroupExpression(); + } + + if (match('[')) { + return parseArrayInitialiser(); + } + + if (match('{')) { + return parseObjectInitialiser(); + } + + type = lookahead.type; + startToken = lookahead; + + if (type === Token.Identifier) { + expr = delegate.createIdentifier(lex().value); + } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { + if (strict && lookahead.octal) { + throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); + } + expr = delegate.createLiteral(lex()); + } else if (type === Token.Keyword) { + if (matchKeyword('function')) { + return parseFunctionExpression(); + } + if (matchKeyword('this')) { + lex(); + expr = delegate.createThisExpression(); + } else { + throwUnexpected(lex()); + } + } else if (type === Token.BooleanLiteral) { + token = lex(); + token.value = (token.value === 'true'); + expr = delegate.createLiteral(token); + } else if (type === Token.NullLiteral) { + token = lex(); + token.value = null; + expr = delegate.createLiteral(token); + } else if (match('/') || match('/=')) { + if (typeof extra.tokens !== 'undefined') { + expr = delegate.createLiteral(collectRegex()); + } else { + expr = delegate.createLiteral(scanRegExp()); + } + peek(); + } else { + throwUnexpected(lex()); + } + + return delegate.markEnd(expr, startToken); + } + + // 11.2 Left-Hand-Side Expressions + + function parseArguments() { + var args = []; + + expect('('); + + if (!match(')')) { + while (index < length) { + args.push(parseAssignmentExpression()); + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + return args; + } + + function parseNonComputedProperty() { + var token, startToken; + + startToken = lookahead; + token = lex(); + + if (!isIdentifierName(token)) { + throwUnexpected(token); + } + + return delegate.markEnd(delegate.createIdentifier(token.value), startToken); + } + + function parseNonComputedMember() { + expect('.'); + + return parseNonComputedProperty(); + } + + function parseComputedMember() { + var expr; + + expect('['); + + expr = parseExpression(); + + expect(']'); + + return expr; + } + + function parseNewExpression() { + var callee, args, startToken; + + startToken = lookahead; + expectKeyword('new'); + callee = parseLeftHandSideExpression(); + args = match('(') ? parseArguments() : []; + + return delegate.markEnd(delegate.createNewExpression(callee, args), startToken); + } + + function parseLeftHandSideExpressionAllowCall() { + var previousAllowIn, expr, args, property, startToken; + + startToken = lookahead; + + previousAllowIn = state.allowIn; + state.allowIn = true; + expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); + state.allowIn = previousAllowIn; + + for (;;) { + if (match('.')) { + property = parseNonComputedMember(); + expr = delegate.createMemberExpression('.', expr, property); + } else if (match('(')) { + args = parseArguments(); + expr = delegate.createCallExpression(expr, args); + } else if (match('[')) { + property = parseComputedMember(); + expr = delegate.createMemberExpression('[', expr, property); + } else { + break; + } + delegate.markEnd(expr, startToken); + } + + return expr; + } + + function parseLeftHandSideExpression() { + var previousAllowIn, expr, property, startToken; + + startToken = lookahead; + + previousAllowIn = state.allowIn; + expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); + state.allowIn = previousAllowIn; + + while (match('.') || match('[')) { + if (match('[')) { + property = parseComputedMember(); + expr = delegate.createMemberExpression('[', expr, property); + } else { + property = parseNonComputedMember(); + expr = delegate.createMemberExpression('.', expr, property); + } + delegate.markEnd(expr, startToken); + } + + return expr; + } + + // 11.3 Postfix Expressions + + function parsePostfixExpression() { + var expr, token, startToken = lookahead; + + expr = parseLeftHandSideExpressionAllowCall(); + + if (lookahead.type === Token.Punctuator) { + if ((match('++') || match('--')) && !peekLineTerminator()) { + // 11.3.1, 11.3.2 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.StrictLHSPostfix); + } + + if (!isLeftHandSide(expr)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + + token = lex(); + expr = delegate.markEnd(delegate.createPostfixExpression(token.value, expr), startToken); + } + } + + return expr; + } + + // 11.4 Unary Operators + + function parseUnaryExpression() { + var token, expr, startToken; + + if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { + expr = parsePostfixExpression(); + } else if (match('++') || match('--')) { + startToken = lookahead; + token = lex(); + expr = parseUnaryExpression(); + // 11.4.4, 11.4.5 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.StrictLHSPrefix); + } + + if (!isLeftHandSide(expr)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + + expr = delegate.createUnaryExpression(token.value, expr); + expr = delegate.markEnd(expr, startToken); + } else if (match('+') || match('-') || match('~') || match('!')) { + startToken = lookahead; + token = lex(); + expr = parseUnaryExpression(); + expr = delegate.createUnaryExpression(token.value, expr); + expr = delegate.markEnd(expr, startToken); + } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { + startToken = lookahead; + token = lex(); + expr = parseUnaryExpression(); + expr = delegate.createUnaryExpression(token.value, expr); + expr = delegate.markEnd(expr, startToken); + if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { + throwErrorTolerant({}, Messages.StrictDelete); + } + } else { + expr = parsePostfixExpression(); + } + + return expr; + } + + function binaryPrecedence(token, allowIn) { + var prec = 0; + + if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { + return 0; + } + + switch (token.value) { + case '||': + prec = 1; + break; + + case '&&': + prec = 2; + break; + + case '|': + prec = 3; + break; + + case '^': + prec = 4; + break; + + case '&': + prec = 5; + break; + + case '==': + case '!=': + case '===': + case '!==': + prec = 6; + break; + + case '<': + case '>': + case '<=': + case '>=': + case 'instanceof': + prec = 7; + break; + + case 'in': + prec = allowIn ? 7 : 0; + break; + + case '<<': + case '>>': + case '>>>': + prec = 8; + break; + + case '+': + case '-': + prec = 9; + break; + + case '*': + case '/': + case '%': + prec = 11; + break; + + default: + break; + } + + return prec; + } + + // 11.5 Multiplicative Operators + // 11.6 Additive Operators + // 11.7 Bitwise Shift Operators + // 11.8 Relational Operators + // 11.9 Equality Operators + // 11.10 Binary Bitwise Operators + // 11.11 Binary Logical Operators + + function parseBinaryExpression() { + var marker, markers, expr, token, prec, stack, right, operator, left, i; + + marker = lookahead; + left = parseUnaryExpression(); + if (left === PlaceHolders.ArrowParameterPlaceHolder) { + return left; + } + + token = lookahead; + prec = binaryPrecedence(token, state.allowIn); + if (prec === 0) { + return left; + } + token.prec = prec; + lex(); + + markers = [marker, lookahead]; + right = parseUnaryExpression(); + + stack = [left, token, right]; + + while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) { + + // Reduce: make a binary expression from the three topmost entries. + while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { + right = stack.pop(); + operator = stack.pop().value; + left = stack.pop(); + expr = delegate.createBinaryExpression(operator, left, right); + markers.pop(); + marker = markers[markers.length - 1]; + delegate.markEnd(expr, marker); + stack.push(expr); + } + + // Shift. + token = lex(); + token.prec = prec; + stack.push(token); + markers.push(lookahead); + expr = parseUnaryExpression(); + stack.push(expr); + } + + // Final reduce to clean-up the stack. + i = stack.length - 1; + expr = stack[i]; + markers.pop(); + while (i > 1) { + expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); + i -= 2; + marker = markers.pop(); + delegate.markEnd(expr, marker); + } + + return expr; + } + + + // 11.12 Conditional Operator + + function parseConditionalExpression() { + var expr, previousAllowIn, consequent, alternate, startToken; + + startToken = lookahead; + + expr = parseBinaryExpression(); + if (expr === PlaceHolders.ArrowParameterPlaceHolder) { + return expr; + } + if (match('?')) { + lex(); + previousAllowIn = state.allowIn; + state.allowIn = true; + consequent = parseAssignmentExpression(); + state.allowIn = previousAllowIn; + expect(':'); + alternate = parseAssignmentExpression(); + + expr = delegate.createConditionalExpression(expr, consequent, alternate); + delegate.markEnd(expr, startToken); + } + + return expr; + } + + // [ES6] 14.2 Arrow Function + + function parseConciseBody() { + if (match('{')) { + return parseFunctionSourceElements(); + } + return parseAssignmentExpression(); + } + + function reinterpretAsCoverFormalsList(expressions) { + var i, len, param, params, defaults, options, rest; + + params = []; + defaults = []; + rest = null; + options = { + paramSet: {} + }; + + for (i = 0, len = expressions.length; i < len; i += 1) { + param = expressions[i]; + if (param.type === Syntax.Identifier) { + params.push(param); + defaults.push(null); + validateParam(options, param, param.name); + } else { + return null; + } + } + + if (options.message === Messages.StrictParamDupe) { + throwError( + strict ? options.stricted : options.firstRestricted, + options.message + ); + } + + return { + params: params, + defaults: defaults, + rest: rest, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + } + + function parseArrowFunctionExpression(options) { + var previousStrict, body; + + expect('=>'); + previousStrict = strict; + + body = parseConciseBody(); + + if (strict && options.firstRestricted) { + throwError(options.firstRestricted, options.message); + } + if (strict && options.stricted) { + throwErrorTolerant(options.stricted, options.message); + } + + strict = previousStrict; + + return delegate.createArrowFunctionExpression(options.params, body, body.type !== Syntax.BlockStatement); + } + + // 11.13 Assignment Operators + + function parseAssignmentExpression() { + var oldParenthesisCount, token, left, right, node, params, list, startToken; + + oldParenthesisCount = state.parenthesisCount; + + startToken = lookahead; + token = lookahead; + + node = left = parseConditionalExpression(); + + if (node === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) { + if (state.parenthesisCount === oldParenthesisCount || + state.parenthesisCount === (oldParenthesisCount + 1)) { + if (node.type === Syntax.Identifier) { + list = reinterpretAsCoverFormalsList([ node ]); + } else if (node.type === Syntax.SequenceExpression) { + list = reinterpretAsCoverFormalsList(node.expressions); + } else if (node === PlaceHolders.ArrowParameterPlaceHolder) { + list = reinterpretAsCoverFormalsList([]); + } + if (list) { + node = parseArrowFunctionExpression(list); + return delegate.markEnd(node, startToken); + } + } + } + + if (matchAssign()) { + // LeftHandSideExpression + if (!isLeftHandSide(left)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + + // 11.13.1 + if (strict && left.type === Syntax.Identifier && isRestrictedWord(left.name)) { + throwErrorTolerant(token, Messages.StrictLHSAssignment); + } + + token = lex(); + right = parseAssignmentExpression(); + node = delegate.markEnd(delegate.createAssignmentExpression(token.value, left, right), startToken); + } + + return node; + } + + // 11.14 Comma Operator + + function parseExpression() { + var expr, startToken = lookahead; + + expr = parseAssignmentExpression(); + + if (match(',')) { + expr = delegate.createSequenceExpression([ expr ]); + + while (index < length) { + if (!match(',')) { + break; + } + lex(); + expr.expressions.push(parseAssignmentExpression()); + } + + delegate.markEnd(expr, startToken); + } + + return expr; + } + + // 12.1 Block + + function parseStatementList() { + var list = [], + statement; + + while (index < length) { + if (match('}')) { + break; + } + statement = parseSourceElement(); + if (typeof statement === 'undefined') { + break; + } + list.push(statement); + } + + return list; + } + + function parseBlock() { + var block, startToken; + + startToken = lookahead; + expect('{'); + + block = parseStatementList(); + + expect('}'); + + return delegate.markEnd(delegate.createBlockStatement(block), startToken); + } + + // 12.2 Variable Statement + + function parseVariableIdentifier() { + var token, startToken; + + startToken = lookahead; + token = lex(); + + if (token.type !== Token.Identifier) { + throwUnexpected(token); + } + + return delegate.markEnd(delegate.createIdentifier(token.value), startToken); + } + + function parseVariableDeclaration(kind) { + var init = null, id, startToken; + + startToken = lookahead; + id = parseVariableIdentifier(); + + // 12.2.1 + if (strict && isRestrictedWord(id.name)) { + throwErrorTolerant({}, Messages.StrictVarName); + } + + if (kind === 'const') { + expect('='); + init = parseAssignmentExpression(); + } else if (match('=')) { + lex(); + init = parseAssignmentExpression(); + } + + return delegate.markEnd(delegate.createVariableDeclarator(id, init), startToken); + } + + function parseVariableDeclarationList(kind) { + var list = []; + + do { + list.push(parseVariableDeclaration(kind)); + if (!match(',')) { + break; + } + lex(); + } while (index < length); + + return list; + } + + function parseVariableStatement() { + var declarations; + + expectKeyword('var'); + + declarations = parseVariableDeclarationList(); + + consumeSemicolon(); + + return delegate.createVariableDeclaration(declarations, 'var'); + } + + // kind may be `const` or `let` + // Both are experimental and not in the specification yet. + // see http://wiki.ecmascript.org/doku.php?id=harmony:const + // and http://wiki.ecmascript.org/doku.php?id=harmony:let + function parseConstLetDeclaration(kind) { + var declarations, startToken; + + startToken = lookahead; + + expectKeyword(kind); + + declarations = parseVariableDeclarationList(kind); + + consumeSemicolon(); + + return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind), startToken); + } + + // 12.3 Empty Statement + + function parseEmptyStatement() { + expect(';'); + return delegate.createEmptyStatement(); + } + + // 12.4 Expression Statement + + function parseExpressionStatement() { + var expr = parseExpression(); + consumeSemicolon(); + return delegate.createExpressionStatement(expr); + } + + // 12.5 If statement + + function parseIfStatement() { + var test, consequent, alternate; + + expectKeyword('if'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + consequent = parseStatement(); + + if (matchKeyword('else')) { + lex(); + alternate = parseStatement(); + } else { + alternate = null; + } + + return delegate.createIfStatement(test, consequent, alternate); + } + + // 12.6 Iteration Statements + + function parseDoWhileStatement() { + var body, test, oldInIteration; + + expectKeyword('do'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + if (match(';')) { + lex(); + } + + return delegate.createDoWhileStatement(body, test); + } + + function parseWhileStatement() { + var test, body, oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + return delegate.createWhileStatement(test, body); + } + + function parseForVariableDeclaration() { + var token, declarations, startToken; + + startToken = lookahead; + token = lex(); + declarations = parseVariableDeclarationList(); + + return delegate.markEnd(delegate.createVariableDeclaration(declarations, token.value), startToken); + } + + function parseForStatement() { + var init, test, update, left, right, body, oldInIteration; + + init = test = update = null; + + expectKeyword('for'); + + expect('('); + + if (match(';')) { + lex(); + } else { + if (matchKeyword('var') || matchKeyword('let')) { + state.allowIn = false; + init = parseForVariableDeclaration(); + state.allowIn = true; + + if (init.declarations.length === 1 && matchKeyword('in')) { + lex(); + left = init; + right = parseExpression(); + init = null; + } + } else { + state.allowIn = false; + init = parseExpression(); + state.allowIn = true; + + if (matchKeyword('in')) { + // LeftHandSideExpression + if (!isLeftHandSide(init)) { + throwErrorTolerant({}, Messages.InvalidLHSInForIn); + } + + lex(); + left = init; + right = parseExpression(); + init = null; + } + } + + if (typeof left === 'undefined') { + expect(';'); + } + } + + if (typeof left === 'undefined') { + + if (!match(';')) { + test = parseExpression(); + } + expect(';'); + + if (!match(')')) { + update = parseExpression(); + } + } + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + return (typeof left === 'undefined') ? + delegate.createForStatement(init, test, update, body) : + delegate.createForInStatement(left, right, body); + } + + // 12.7 The continue statement + + function parseContinueStatement() { + var label = null, key; + + expectKeyword('continue'); + + // Optimize the most common form: 'continue;'. + if (source.charCodeAt(index) === 0x3B) { + lex(); + + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return delegate.createContinueStatement(null); + } + + if (peekLineTerminator()) { + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return delegate.createContinueStatement(null); + } + + if (lookahead.type === Token.Identifier) { + label = parseVariableIdentifier(); + + key = '$' + label.name; + if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return delegate.createContinueStatement(label); + } + + // 12.8 The break statement + + function parseBreakStatement() { + var label = null, key; + + expectKeyword('break'); + + // Catch the very common case first: immediately a semicolon (U+003B). + if (source.charCodeAt(index) === 0x3B) { + lex(); + + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return delegate.createBreakStatement(null); + } + + if (peekLineTerminator()) { + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return delegate.createBreakStatement(null); + } + + if (lookahead.type === Token.Identifier) { + label = parseVariableIdentifier(); + + key = '$' + label.name; + if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return delegate.createBreakStatement(label); + } + + // 12.9 The return statement + + function parseReturnStatement() { + var argument = null; + + expectKeyword('return'); + + if (!state.inFunctionBody) { + throwErrorTolerant({}, Messages.IllegalReturn); + } + + // 'return' followed by a space and an identifier is very common. + if (source.charCodeAt(index) === 0x20) { + if (isIdentifierStart(source.charCodeAt(index + 1))) { + argument = parseExpression(); + consumeSemicolon(); + return delegate.createReturnStatement(argument); + } + } + + if (peekLineTerminator()) { + return delegate.createReturnStatement(null); + } + + if (!match(';')) { + if (!match('}') && lookahead.type !== Token.EOF) { + argument = parseExpression(); + } + } + + consumeSemicolon(); + + return delegate.createReturnStatement(argument); + } + + // 12.10 The with statement + + function parseWithStatement() { + var object, body; + + if (strict) { + // TODO(ikarienator): Should we update the test cases instead? + skipComment(); + throwErrorTolerant({}, Messages.StrictModeWith); + } + + expectKeyword('with'); + + expect('('); + + object = parseExpression(); + + expect(')'); + + body = parseStatement(); + + return delegate.createWithStatement(object, body); + } + + // 12.10 The swith statement + + function parseSwitchCase() { + var test, consequent = [], statement, startToken; + + startToken = lookahead; + if (matchKeyword('default')) { + lex(); + test = null; + } else { + expectKeyword('case'); + test = parseExpression(); + } + expect(':'); + + while (index < length) { + if (match('}') || matchKeyword('default') || matchKeyword('case')) { + break; + } + statement = parseStatement(); + consequent.push(statement); + } + + return delegate.markEnd(delegate.createSwitchCase(test, consequent), startToken); + } + + function parseSwitchStatement() { + var discriminant, cases, clause, oldInSwitch, defaultFound; + + expectKeyword('switch'); + + expect('('); + + discriminant = parseExpression(); + + expect(')'); + + expect('{'); + + cases = []; + + if (match('}')) { + lex(); + return delegate.createSwitchStatement(discriminant, cases); + } + + oldInSwitch = state.inSwitch; + state.inSwitch = true; + defaultFound = false; + + while (index < length) { + if (match('}')) { + break; + } + clause = parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + throwError({}, Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + + state.inSwitch = oldInSwitch; + + expect('}'); + + return delegate.createSwitchStatement(discriminant, cases); + } + + // 12.13 The throw statement + + function parseThrowStatement() { + var argument; + + expectKeyword('throw'); + + if (peekLineTerminator()) { + throwError({}, Messages.NewlineAfterThrow); + } + + argument = parseExpression(); + + consumeSemicolon(); + + return delegate.createThrowStatement(argument); + } + + // 12.14 The try statement + + function parseCatchClause() { + var param, body, startToken; + + startToken = lookahead; + expectKeyword('catch'); + + expect('('); + if (match(')')) { + throwUnexpected(lookahead); + } + + param = parseVariableIdentifier(); + // 12.14.1 + if (strict && isRestrictedWord(param.name)) { + throwErrorTolerant({}, Messages.StrictCatchVariable); + } + + expect(')'); + body = parseBlock(); + return delegate.markEnd(delegate.createCatchClause(param, body), startToken); + } + + function parseTryStatement() { + var block, handlers = [], finalizer = null; + + expectKeyword('try'); + + block = parseBlock(); + + if (matchKeyword('catch')) { + handlers.push(parseCatchClause()); + } + + if (matchKeyword('finally')) { + lex(); + finalizer = parseBlock(); + } + + if (handlers.length === 0 && !finalizer) { + throwError({}, Messages.NoCatchOrFinally); + } + + return delegate.createTryStatement(block, [], handlers, finalizer); + } + + // 12.15 The debugger statement + + function parseDebuggerStatement() { + expectKeyword('debugger'); + + consumeSemicolon(); + + return delegate.createDebuggerStatement(); + } + + // 12 Statements + + function parseStatement() { + var type = lookahead.type, + expr, + labeledBody, + key, + startToken; + + if (type === Token.EOF) { + throwUnexpected(lookahead); + } + + if (type === Token.Punctuator && lookahead.value === '{') { + return parseBlock(); + } + + startToken = lookahead; + + if (type === Token.Punctuator) { + switch (lookahead.value) { + case ';': + return delegate.markEnd(parseEmptyStatement(), startToken); + case '(': + return delegate.markEnd(parseExpressionStatement(), startToken); + default: + break; + } + } + + if (type === Token.Keyword) { + switch (lookahead.value) { + case 'break': + return delegate.markEnd(parseBreakStatement(), startToken); + case 'continue': + return delegate.markEnd(parseContinueStatement(), startToken); + case 'debugger': + return delegate.markEnd(parseDebuggerStatement(), startToken); + case 'do': + return delegate.markEnd(parseDoWhileStatement(), startToken); + case 'for': + return delegate.markEnd(parseForStatement(), startToken); + case 'function': + return delegate.markEnd(parseFunctionDeclaration(), startToken); + case 'if': + return delegate.markEnd(parseIfStatement(), startToken); + case 'return': + return delegate.markEnd(parseReturnStatement(), startToken); + case 'switch': + return delegate.markEnd(parseSwitchStatement(), startToken); + case 'throw': + return delegate.markEnd(parseThrowStatement(), startToken); + case 'try': + return delegate.markEnd(parseTryStatement(), startToken); + case 'var': + return delegate.markEnd(parseVariableStatement(), startToken); + case 'while': + return delegate.markEnd(parseWhileStatement(), startToken); + case 'with': + return delegate.markEnd(parseWithStatement(), startToken); + default: + break; + } + } + + expr = parseExpression(); + + // 12.12 Labelled Statements + if ((expr.type === Syntax.Identifier) && match(':')) { + lex(); + + key = '$' + expr.name; + if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + throwError({}, Messages.Redeclaration, 'Label', expr.name); + } + + state.labelSet[key] = true; + labeledBody = parseStatement(); + delete state.labelSet[key]; + return delegate.markEnd(delegate.createLabeledStatement(expr, labeledBody), startToken); + } + + consumeSemicolon(); + + return delegate.markEnd(delegate.createExpressionStatement(expr), startToken); + } + + // 13 Function Definition + + function parseFunctionSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted, + oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount, + startToken; + + startToken = lookahead; + expect('{'); + + while (index < length) { + if (lookahead.type !== Token.StringLiteral) { + break; + } + token = lookahead; + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = source.slice(token.start + 1, token.end - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + oldLabelSet = state.labelSet; + oldInIteration = state.inIteration; + oldInSwitch = state.inSwitch; + oldInFunctionBody = state.inFunctionBody; + oldParenthesisCount = state.parenthesizedCount; + + state.labelSet = {}; + state.inIteration = false; + state.inSwitch = false; + state.inFunctionBody = true; + state.parenthesizedCount = 0; + + while (index < length) { + if (match('}')) { + break; + } + sourceElement = parseSourceElement(); + if (typeof sourceElement === 'undefined') { + break; + } + sourceElements.push(sourceElement); + } + + expect('}'); + + state.labelSet = oldLabelSet; + state.inIteration = oldInIteration; + state.inSwitch = oldInSwitch; + state.inFunctionBody = oldInFunctionBody; + state.parenthesizedCount = oldParenthesisCount; + + return delegate.markEnd(delegate.createBlockStatement(sourceElements), startToken); + } + + function validateParam(options, param, name) { + var key = '$' + name; + if (strict) { + if (isRestrictedWord(name)) { + options.stricted = param; + options.message = Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = Messages.StrictParamDupe; + } + } else if (!options.firstRestricted) { + if (isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictParamName; + } else if (isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictReservedWord; + } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.firstRestricted = param; + options.message = Messages.StrictParamDupe; + } + } + options.paramSet[key] = true; + } + + function parseParams(firstRestricted) { + var param, options, token, message; + + options = { + params: [], + firstRestricted: firstRestricted + }; + + expect('('); + + if (!match(')')) { + options.paramSet = {}; + while (index < length) { + token = lookahead; + param = parseVariableIdentifier(); + validateParam(options, token, token.value); + options.params.push(param); + if (match(')')) { + break; + } + expect(','); + } + } + + expect(')'); + + return { + params: options.params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + } + + function parseFunctionDeclaration() { + var id, params = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, startToken; + + startToken = lookahead; + + expectKeyword('function'); + token = lookahead; + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + + tmp = parseParams(firstRestricted); + params = tmp.params; + stricted = tmp.stricted; + firstRestricted = tmp.firstRestricted; + if (tmp.message) { + message = tmp.message; + } + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + if (strict && stricted) { + throwErrorTolerant(stricted, message); + } + strict = previousStrict; + + return delegate.markEnd(delegate.createFunctionDeclaration(id, params, [], body), startToken); + } + + function parseFunctionExpression() { + var token, id = null, stricted, firstRestricted, message, tmp, params = [], body, previousStrict, startToken; + + startToken = lookahead; + expectKeyword('function'); + + if (!match('(')) { + token = lookahead; + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + } + + tmp = parseParams(firstRestricted); + params = tmp.params; + stricted = tmp.stricted; + firstRestricted = tmp.firstRestricted; + if (tmp.message) { + message = tmp.message; + } + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + if (strict && stricted) { + throwErrorTolerant(stricted, message); + } + strict = previousStrict; + + return delegate.markEnd(delegate.createFunctionExpression(id, params, [], body), startToken); + } + + // 14 Program + + function parseSourceElement() { + if (lookahead.type === Token.Keyword) { + switch (lookahead.value) { + case 'const': + case 'let': + return parseConstLetDeclaration(lookahead.value); + case 'function': + return parseFunctionDeclaration(); + default: + return parseStatement(); + } + } + + if (lookahead.type !== Token.EOF) { + return parseStatement(); + } + } + + function parseSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted; + + while (index < length) { + token = lookahead; + if (token.type !== Token.StringLiteral) { + break; + } + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = source.slice(token.start + 1, token.end - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + while (index < length) { + sourceElement = parseSourceElement(); + /* istanbul ignore if */ + if (typeof sourceElement === 'undefined') { + break; + } + sourceElements.push(sourceElement); + } + return sourceElements; + } + + function parseProgram() { + var body, startToken; + + skipComment(); + peek(); + startToken = lookahead; + strict = false; + + body = parseSourceElements(); + return delegate.markEnd(delegate.createProgram(body), startToken); + } + + function filterTokenLocation() { + var i, entry, token, tokens = []; + + for (i = 0; i < extra.tokens.length; ++i) { + entry = extra.tokens[i]; + token = { + type: entry.type, + value: entry.value + }; + if (extra.range) { + token.range = entry.range; + } + if (extra.loc) { + token.loc = entry.loc; + } + tokens.push(token); + } + + extra.tokens = tokens; + } + + function tokenize(code, options) { + var toString, + token, + tokens; + + toString = String; + if (typeof code !== 'string' && !(code instanceof String)) { + code = toString(code); + } + + delegate = SyntaxTreeDelegate; + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + length = source.length; + lookahead = null; + state = { + allowIn: true, + labelSet: {}, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + lastCommentStart: -1 + }; + + extra = {}; + + // Options matching. + options = options || {}; + + // Of course we collect tokens here. + options.tokens = true; + extra.tokens = []; + extra.tokenize = true; + // The following two fields are necessary to compute the Regex tokens. + extra.openParenToken = -1; + extra.openCurlyToken = -1; + + extra.range = (typeof options.range === 'boolean') && options.range; + extra.loc = (typeof options.loc === 'boolean') && options.loc; + + if (typeof options.comment === 'boolean' && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === 'boolean' && options.tolerant) { + extra.errors = []; + } + + try { + peek(); + if (lookahead.type === Token.EOF) { + return extra.tokens; + } + + token = lex(); + while (lookahead.type !== Token.EOF) { + try { + token = lex(); + } catch (lexError) { + token = lookahead; + if (extra.errors) { + extra.errors.push(lexError); + // We have to break on the first error + // to avoid infinite loops. + break; + } else { + throw lexError; + } + } + } + + filterTokenLocation(); + tokens = extra.tokens; + if (typeof extra.comments !== 'undefined') { + tokens.comments = extra.comments; + } + if (typeof extra.errors !== 'undefined') { + tokens.errors = extra.errors; + } + } catch (e) { + throw e; + } finally { + extra = {}; + } + return tokens; + } + + function parse(code, options) { + var program, toString; + + toString = String; + if (typeof code !== 'string' && !(code instanceof String)) { + code = toString(code); + } + + delegate = SyntaxTreeDelegate; + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + length = source.length; + lookahead = null; + state = { + allowIn: true, + labelSet: {}, + parenthesisCount: 0, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + lastCommentStart: -1 + }; + + extra = {}; + if (typeof options !== 'undefined') { + extra.range = (typeof options.range === 'boolean') && options.range; + extra.loc = (typeof options.loc === 'boolean') && options.loc; + extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; + + if (extra.loc && options.source !== null && options.source !== undefined) { + extra.source = toString(options.source); + } + + if (typeof options.tokens === 'boolean' && options.tokens) { + extra.tokens = []; + } + if (typeof options.comment === 'boolean' && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === 'boolean' && options.tolerant) { + extra.errors = []; + } + if (extra.attachComment) { + extra.range = true; + extra.comments = []; + extra.bottomRightStack = []; + extra.trailingComments = []; + extra.leadingComments = []; + } + } + + try { + program = parseProgram(); + if (typeof extra.comments !== 'undefined') { + program.comments = extra.comments; + } + if (typeof extra.tokens !== 'undefined') { + filterTokenLocation(); + program.tokens = extra.tokens; + } + if (typeof extra.errors !== 'undefined') { + program.errors = extra.errors; + } + } catch (e) { + throw e; + } finally { + extra = {}; + } + + return program; + } + + // Sync with *.json manifests. + exports.version = '2.0.0-dev'; + + exports.tokenize = tokenize; + + exports.parse = parse; + + // Deep copy. + /* istanbul ignore next */ + exports.Syntax = (function () { + var name, types = {}; + + if (typeof Object.create === 'function') { + types = Object.create(null); + } + + for (name in Syntax) { + if (Syntax.hasOwnProperty(name)) { + types[name] = Syntax[name]; + } + } + + if (typeof Object.freeze === 'function') { + Object.freeze(types); + } + + return types; + }()); + +})); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/scripts/lib/esprima-master/examples/detectnestedternary.js b/scripts/lib/esprima-master/examples/detectnestedternary.js new file mode 100755 index 0000000..f144955 --- /dev/null +++ b/scripts/lib/esprima-master/examples/detectnestedternary.js @@ -0,0 +1,106 @@ +// Usage: node detectnestedternary.js /path/to/some/directory +// For more details, please read http://esprima.org/doc/#nestedternary + +/*jslint node:true sloppy:true plusplus:true */ + +var fs = require('fs'), + esprima = require('../esprima'), + dirname = process.argv[2]; + + +// Executes visitor on the object and its children (recursively). +function traverse(object, visitor) { + var key, child; + + visitor.call(null, object); + for (key in object) { + if (object.hasOwnProperty(key)) { + child = object[key]; + if (typeof child === 'object' && child !== null) { + traverse(child, visitor); + } + } + } +} + +// http://stackoverflow.com/q/5827612/ +function walk(dir, done) { + var results = []; + fs.readdir(dir, function (err, list) { + if (err) { + return done(err); + } + var i = 0; + (function next() { + var file = list[i++]; + if (!file) { + return done(null, results); + } + file = dir + '/' + file; + fs.stat(file, function (err, stat) { + if (stat && stat.isDirectory()) { + walk(file, function (err, res) { + results = results.concat(res); + next(); + }); + } else { + results.push(file); + next(); + } + }); + }()); + }); +} + +walk(dirname, function (err, results) { + if (err) { + console.log('Error', err); + return; + } + + results.forEach(function (filename) { + var shortname, first, content, syntax; + + shortname = filename; + first = true; + + if (shortname.substr(0, dirname.length) === dirname) { + shortname = shortname.substr(dirname.length + 1, shortname.length); + } + + function report(node, problem) { + if (first === true) { + console.log(shortname + ': '); + first = false; + } + console.log(' Line', node.loc.start.line, ':', problem); + } + + function checkConditional(node) { + var condition; + + if (node.consequent.type === 'ConditionalExpression' || + node.alternate.type === 'ConditionalExpression') { + + condition = content.substring(node.test.range[0], node.test.range[1]); + if (condition.length > 20) { + condition = condition.substring(0, 20) + '...'; + } + condition = '"' + condition + '"'; + report(node, 'Nested ternary for ' + condition); + } + } + + try { + content = fs.readFileSync(filename, 'utf-8'); + syntax = esprima.parse(content, { tolerant: true, loc: true, range: true }); + traverse(syntax, function (node) { + if (node.type === 'ConditionalExpression') { + checkConditional(node); + } + }); + } catch (e) { + } + + }); +}); diff --git a/scripts/lib/esprima-master/examples/findbooleantrap.js b/scripts/lib/esprima-master/examples/findbooleantrap.js new file mode 100755 index 0000000..dc6d1d9 --- /dev/null +++ b/scripts/lib/esprima-master/examples/findbooleantrap.js @@ -0,0 +1,173 @@ +// Usage: node findbooleantrap.js /path/to/some/directory +// For more details, please read http://esprima.org/doc/#booleantrap. + +/*jslint node:true sloppy:true plusplus:true */ + +var fs = require('fs'), + esprima = require('../esprima'), + dirname = process.argv[2], + doubleNegativeList = []; + + +// Black-list of terms with double-negative meaning. +doubleNegativeList = [ + 'hidden', + 'caseinsensitive', + 'disabled' +]; + + +// Executes visitor on the object and its children (recursively). +function traverse(object, visitor) { + var key, child; + + if (visitor.call(null, object) === false) { + return; + } + for (key in object) { + if (object.hasOwnProperty(key)) { + child = object[key]; + if (typeof child === 'object' && child !== null) { + traverse(child, visitor); + } + } + } +} + +// http://stackoverflow.com/q/5827612/ +function walk(dir, done) { + var results = []; + fs.readdir(dir, function (err, list) { + if (err) { + return done(err); + } + var i = 0; + (function next() { + var file = list[i++]; + if (!file) { + return done(null, results); + } + file = dir + '/' + file; + fs.stat(file, function (err, stat) { + if (stat && stat.isDirectory()) { + walk(file, function (err, res) { + results = results.concat(res); + next(); + }); + } else { + results.push(file); + next(); + } + }); + }()); + }); +} + +walk(dirname, function (err, results) { + if (err) { + console.log('Error', err); + return; + } + + results.forEach(function (filename) { + var shortname, first, content, syntax; + + shortname = filename; + first = true; + + if (shortname.substr(0, dirname.length) === dirname) { + shortname = shortname.substr(dirname.length + 1, shortname.length); + } + + function getFunctionName(node) { + if (node.callee.type === 'Identifier') { + return node.callee.name; + } + if (node.callee.type === 'MemberExpression') { + return node.callee.property.name; + } + } + + function report(node, problem) { + if (first === true) { + console.log(shortname + ': '); + first = false; + } + console.log(' Line', node.loc.start.line, 'in function', + getFunctionName(node) + ':', problem); + } + + function checkSingleArgument(node) { + var args = node['arguments'], + functionName = getFunctionName(node); + + if ((args.length !== 1) || (typeof args[0].value !== 'boolean')) { + return; + } + + // Check if the method is a setter, i.e. starts with 'set', + // e.g. 'setEnabled(false)'. + if (functionName.substr(0, 3) !== 'set') { + report(node, 'Boolean literal with a non-setter function'); + } + + // Does it contain a term with double-negative meaning? + doubleNegativeList.forEach(function (term) { + if (functionName.toLowerCase().indexOf(term.toLowerCase()) >= 0) { + report(node, 'Boolean literal with confusing double-negative'); + } + }); + } + + function checkMultipleArguments(node) { + var args = node['arguments'], + literalCount = 0; + + args.forEach(function (arg) { + if (typeof arg.value === 'boolean') { + literalCount++; + } + }); + + // At least two arguments must be Boolean literals. + if (literalCount >= 2) { + + // Check for two different Boolean literals in one call. + if (literalCount === 2 && args.length === 2) { + if (args[0].value !== args[1].value) { + report(node, 'Confusing true vs false'); + return; + } + } + + report(node, 'Multiple Boolean literals'); + } + } + + function checkLastArgument(node) { + var args = node['arguments']; + + if (args.length < 2) { + return; + } + + if (typeof args[args.length - 1].value === 'boolean') { + report(node, 'Ambiguous Boolean literal as the last argument'); + } + } + + try { + content = fs.readFileSync(filename, 'utf-8'); + syntax = esprima.parse(content, { tolerant: true, loc: true }); + traverse(syntax, function (node) { + if (node.type === 'CallExpression') { + checkSingleArgument(node); + checkLastArgument(node); + checkMultipleArguments(node); + } + }); + } catch (e) { + } + + }); +}); diff --git a/scripts/lib/esprima-master/examples/tokendist.js b/scripts/lib/esprima-master/examples/tokendist.js new file mode 100755 index 0000000..bdd7761 --- /dev/null +++ b/scripts/lib/esprima-master/examples/tokendist.js @@ -0,0 +1,33 @@ +/*jslint node:true */ +var fs = require('fs'), + esprima = require('../esprima'), + files = process.argv.splice(2), + histogram, + type; + +histogram = { + Boolean: 0, + Identifier: 0, + Keyword: 0, + Null: 0, + Numeric: 0, + Punctuator: 0, + RegularExpression: 0, + String: 0 +}; + +files.forEach(function (filename) { + 'use strict'; + var content = fs.readFileSync(filename, 'utf-8'), + tokens = esprima.parse(content, { tokens: true }).tokens; + + tokens.forEach(function (token) { + histogram[token.type] += 1; + }); +}); + +for (type in histogram) { + if (histogram.hasOwnProperty(type)) { + console.log(type, histogram[type]); + } +} diff --git a/scripts/lib/esprima-master/index.html b/scripts/lib/esprima-master/index.html new file mode 100755 index 0000000..e87669b --- /dev/null +++ b/scripts/lib/esprima-master/index.html @@ -0,0 +1,138 @@ + + + + + + + Esprima + + + + + + + + + + + +
+
+

ECMAScript parsing infrastructure for multipurpose analysis

+
+
+ + +
+
+

Esprima is a high performance, standard-compliant + ECMAScript parser written in ECMAScript (also popularly known as + JavaScript).

+ +
+
+

Features

+ +

+

Esprima serves as an important building block for some JavaScript language tools, + from code instrumentation to editor autocompletion.

+ Autocomplete

+
+
+
+ +
+
+

Once the full syntax tree is obtained, various static code analysis + can be applied to give an insight to the code: + syntax visualization, + code validation, + editing autocomplete (with type inferencing) + and many others.

+
+
+

Regenerating the code from the syntax tree permits a few different types of code transformation, + from a simple rewriting (with specific formatting) to + a more complicated minification.

+
+

Esprima runs on many popular web browsers, as well as other ECMAScript platforms such as + Rhino, + Nashorn, and + Node.js. It is distributed under the + BSD license.

+
+
+ + + + + + diff --git a/scripts/lib/esprima-master/package.json b/scripts/lib/esprima-master/package.json new file mode 100755 index 0000000..220a1fe --- /dev/null +++ b/scripts/lib/esprima-master/package.json @@ -0,0 +1,83 @@ +{ + "name": "esprima", + "description": "ECMAScript parsing infrastructure for multipurpose analysis", + "homepage": "http://esprima.org", + "main": "esprima.js", + "bin": { + "esparse": "./bin/esparse.js", + "esvalidate": "./bin/esvalidate.js" + }, + "version": "2.0.0-dev", + "files": [ + "bin", + "test/run.js", + "test/runner.js", + "test/test.js", + "test/compat.js", + "test/reflect.js", + "esprima.js" + ], + "engines": { + "node": ">=0.4.0" + }, + "author": { + "name": "Ariya Hidayat", + "email": "ariya.hidayat@gmail.com" + }, + "maintainers": [{ + "name": "Ariya Hidayat", + "email": "ariya.hidayat@gmail.com", + "web": "http://ariya.ofilabs.com" + }], + "repository": { + "type": "git", + "url": "http://github.com/ariya/esprima.git" + }, + "bugs": { + "url": "http://issues.esprima.org" + }, + "licenses": [{ + "type": "BSD", + "url": "http://github.com/ariya/esprima/raw/master/LICENSE.BSD" + }], + "devDependencies": { + "jslint": "~0.1.9", + "eslint": "~0.4.3", + "jscs": "~1.2.4", + "istanbul": "~0.2.6", + "complexity-report": "~0.6.1", + "regenerate": "~0.5.4", + "unicode-6.3.0": "~0.1.0", + "json-diff": "~0.3.1", + "optimist": "~0.6.0" + }, + "keywords": [ + "ast", + "ecmascript", + "javascript", + "parser", + "syntax" + ], + "scripts": { + "generate-regex": "node tools/generate-identifier-regex.js", + + "test": "npm run-script lint && node test/run.js && npm run-script coverage && npm run-script complexity", + + "lint": "npm run-script check-version && npm run-script eslint && npm run-script jscs && npm run-script jslint", + "check-version": "node tools/check-version.js", + "eslint": "node node_modules/eslint/bin/eslint.js esprima.js", + "jscs": "node node_modules/.bin/jscs esprima.js", + "jslint": "node node_modules/jslint/bin/jslint.js esprima.js", + + "coverage": "npm run-script analyze-coverage && npm run-script check-coverage", + "analyze-coverage": "node node_modules/istanbul/lib/cli.js cover test/runner.js", + "check-coverage": "node node_modules/istanbul/lib/cli.js check-coverage --statement 100 --branch 100 --function 100", + + "complexity": "npm run-script analyze-complexity && npm run-script check-complexity", + "analyze-complexity": "node tools/list-complexity.js", + "check-complexity": "node node_modules/complexity-report/src/cli.js --maxcc 14 --silent -l -w esprima.js", + + "benchmark": "node test/benchmarks.js", + "benchmark-quick": "node test/benchmarks.js quick" + } +} diff --git a/scripts/lib/esprima-master/tools/check-version.js b/scripts/lib/esprima-master/tools/check-version.js new file mode 100755 index 0000000..2d4d82e --- /dev/null +++ b/scripts/lib/esprima-master/tools/check-version.js @@ -0,0 +1,57 @@ +#!/usr/bin/env node + +'use strict'; + +var fs = require('fs'); + +function findCanonicalVersion() { + var matcher, lines, version; + + matcher = /exports\.version\s+=\s+\'([0-9\.\-a-zA-Z]+)\'/; + lines = fs.readFileSync('esprima.js', 'utf-8').split('\n'); + lines.forEach(function (line) { + if (matcher.test(line)) { + version = matcher.exec(line)[1]; + } + }); + + return version; +} + +function ensureVersion(manifestFile, expectedVersion) { + var matcher, lines, version; + + console.log('Checking', manifestFile, '...'); + matcher = /"version"\s*\:\s*"([0-9\.\-a-zA-Z]+)"/; + lines = fs.readFileSync(manifestFile, 'utf-8').split('\n'); + lines.forEach(function (line) { + if (matcher.test(line)) { + version = matcher.exec(line)[1]; + } + }); + if (expectedVersion !== version) { + console.log('ERROR: Wrong version for', manifestFile); + console.log('Expected:', expectedVersion); + console.log(' Actual:', version); + process.exit(1); + } +} + +function checkVersion() { + var version; + + console.log('Getting the canonical library version...'); + version = findCanonicalVersion(); + if (typeof version !== 'string') { + console.log('ERROR: Can not get version number!', typeof version); + process.exit(1); + } + console.log('Library version is', version); + + ensureVersion('package.json', version); + ensureVersion('bower.json', version); + ensureVersion('component.json', version); +} + + +checkVersion(); diff --git a/scripts/lib/esprima-master/tools/generate-identifier-regex.js b/scripts/lib/esprima-master/tools/generate-identifier-regex.js new file mode 100755 index 0000000..8b3ab14 --- /dev/null +++ b/scripts/lib/esprima-master/tools/generate-identifier-regex.js @@ -0,0 +1,52 @@ +// Based on https://gist.github.com/mathiasbynens/6334847 by @mathias + +var regenerate = require('regenerate'); + +// Which Unicode version should be used? +var version = '6.3.0'; // note: also update `package.json` when this changes + +// Shorthand function +var get = function(what) { + return require('unicode-' + version + '/' + what + '/code-points'); +}; + +// Unicode categories needed to construct the ES5 regex +var Lu = get('categories/Lu'); +var Ll = get('categories/Ll'); +var Lt = get('categories/Lt'); +var Lm = get('categories/Lm'); +var Lo = get('categories/Lo'); +var Nl = get('categories/Nl'); +var Mn = get('categories/Mn'); +var Mc = get('categories/Mc'); +var Nd = get('categories/Nd'); +var Pc = get('categories/Pc'); + +var generateES5Regex = function() { // ES 5.1 + // http://mathiasbynens.be/notes/javascript-identifiers#valid-identifier-names + var identifierStart = regenerate('$', '_') + .add(Lu, Ll, Lt, Lm, Lo, Nl) + .removeRange(0x010000, 0x10FFFF) // remove astral symbols + .removeRange(0x0, 0x7F); // remove ASCII symbols (Esprima-specific) + var identifierStartCodePoints = identifierStart.toArray(); + var identifierPart = regenerate(identifierStartCodePoints) + .add('\u200C', '\u200D', Mn, Mc, Nd, Pc) + .removeRange(0x010000, 0x10FFFF) // remove astral symbols + .removeRange(0x0, 0x7F); // remove ASCII symbols (Esprima-specific) + return { + 'NonAsciiIdentifierStart': identifierStart.toString(), + 'NonAsciiIdentifierPart': identifierPart.toString() + }; +}; + +var result = generateES5Regex(); +console.log( + '// ECMAScript 5.1/Unicode v%s NonAsciiIdentifierStart:\n\n%s\n', + version, + result.NonAsciiIdentifierStart +); +console.log( + '// ECMAScript 5.1/Unicode v%s NonAsciiIdentifierPart:\n\n%s', + version, + result.NonAsciiIdentifierPart +); diff --git a/scripts/lib/esprima-master/tools/generate-test-fixture.js b/scripts/lib/esprima-master/tools/generate-test-fixture.js new file mode 100755 index 0000000..7131f61 --- /dev/null +++ b/scripts/lib/esprima-master/tools/generate-test-fixture.js @@ -0,0 +1,336 @@ +// #!/usr/bin/env node +/* + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2011 Ariya Hidayat + + 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 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 */ +/*global str:true */ +(function () { + 'use strict'; + var fs = require('fs'), + optimist = require('optimist'), + path = require('path'), + root = path.join(path.dirname(fs.realpathSync(__filename)), '..'), + esprima = require(path.join(root, 'esprima')), + code = process.argv.splice(2), + content, + options; + + if (code.length === 0) { + console.log('Usage:'); + console.log(' generate-test-fixture.js code'); + process.exit(1); + } + + // This function is based on ECMA262 section 15.12.3JSON.stringify algorithm with modification + function stringify(given, printStrictJSON) { + + var Regex, gap, top, indent; + + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), + NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') + }; + + function isIdentifierStart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch)); + } + + function isIdentifierPart(ch) { + return (ch === '$') || (ch === '_') || (ch === '\\') || + (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + ((ch >= '0') && (ch <= '9')) || + ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch)); + } + + // 7.6.1.2 Future Reserved Words + + function isFutureReservedWord(id) { + switch (id) { + + // Future reserved words. + case 'class': + case 'enum': + case 'export': + case 'extends': + case 'import': + case 'super': + return true; + } + + return false; + } + + function isStrictModeReservedWord(id) { + switch (id) { + + // Strict Mode reserved words. + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'yield': + case 'let': + return true; + } + + return false; + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + // 7.6.1.1 Keywords + + function isKeyword(id) { + var keyword = false; + switch (id.length) { + case 2: + keyword = (id === 'if') || (id === 'in') || (id === 'do'); + break; + case 3: + keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); + break; + case 4: + keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with'); + break; + case 5: + keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw'); + break; + case 6: + keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch'); + break; + case 7: + keyword = (id === 'default') || (id === 'finally'); + break; + case 8: + keyword = (id === 'function') || (id === 'continue') || (id === 'debugger'); + break; + case 10: + keyword = (id === 'instanceof'); + break; + } + + if (keyword) { + return true; + } + + switch (id) { + // Future reserved words. + // 'const' is specialized as Keyword in V8. + case 'const': + return true; + + // For compatiblity to SpiderMonkey and ES.next + case 'yield': + case 'let': + return true; + } + + if (isStrictModeReservedWord(id)) { + return true; + } + + return isFutureReservedWord(id); + } + + function isIdentifier(name) { + var i, iz; + // fallback for ES3 + if (isKeyword(name) || isRestrictedWord(name)) { + return false; + } + if (name.length === 0) { + return false; + } + if (!isIdentifierStart(name.charAt(0))) { + return false; + } + for (i = 1, iz = name.length; i < iz; i += 1) { + if (!isIdentifierPart(name.charAt(i))) { + return false; + } + } + return true; + } + + function quote(string) { + var i, iz, ch, product, hex; + product = '"'; + for (i = 0, iz = string.length; i < iz; i += 1) { + ch = string[i]; + if (ch === '"' || ch === '\\') { + product += '\\'; + product += ch; + } else { + switch (ch) { + case '\b': + product += '\\b'; + break; + case '\f': + product += '\\f'; + break; + case '\n': + product += '\\n'; + break; + case '\r': + product += '\\r'; + break; + case '\t': + product += '\\t'; + break; + case '\u2028': + product += '\u2028'; + break; + case '\u2029': + product += '\u2028'; + break; + default: + if (ch < ' ') { + hex = ch.toString(16); + product += '\\u' + '0000'.slice(hex.length) + hex; + } else { + product += ch; + } + } + } + } + return product + '"'; + } + + function ja(array) { + return '[' + array.map(function (elm, key) { + return str(key, array); + }).join(', ') + ']'; + } + + function jo(object, key) { + var stepback, partial, fin, separator, + startStr = 'start', endStr = 'end', lineStr = 'line', colStr = 'column'; + + if (printStrictJSON) { + startStr = '"' + startStr + '"'; + endStr = '"' + endStr + '"'; + lineStr = '"' + lineStr + '"'; + colStr = '"' + colStr + '"'; + } + + stepback = indent; + indent += gap; + + if (key === 'loc') { + // specialized for loc + fin = '{\n' + + indent + startStr + ': { ' + lineStr + ': ' + stringify(object.start.line) + ', ' + colStr + ': ' + stringify(object.start.column) + ' },\n' + + indent + endStr + ': { ' + lineStr + ': ' + stringify(object.end.line) + ', ' + colStr + ': ' + stringify(object.end.column) + ' }\n' + + stepback + '}'; + } else { + partial = Object.keys(object).reduce(function (partial, name) { + var res; + res = str(name, object); + if (res !== undefined) { + if (printStrictJSON || !isIdentifier(name)) { + name = quote(name); + } + partial.push(name + ': ' + res); + } + return partial; + }, []); + + if (!partial.length) { + fin = '{}'; + } else { + fin = '{\n' + indent + partial.join(',\n' + indent) + '\n' + stepback + '}'; + } + } + + indent = stepback; + return fin; + } + + function str(key, holder) { + var value; + value = holder[key]; + if (typeof value === 'object' && value !== null) { + if (value instanceof Number) { + value = Number(value); + } + if (value instanceof String) { + value = String(value); + } + if (value instanceof Boolean) { + value = Boolean(value); + } + } + switch (typeof value) { + case 'object': + if (value === null) { + return 'null'; + } + if (Array.isArray(value)) { + return ja(value); + } + return jo(value, key); + + case 'boolean': + return String(value); + case 'string': + return quote(value); + case 'number': + return JSON.stringify(value); + } + } + + gap = ' '; + indent = ''; + top = {}; + top[''] = given; + + return str('', top); + } + + content = code[0]; + + options = { + comment: false, + range: true, + loc: true, + tokens: false, + raw: true, + tolerant: false + }; + + console.log(stringify( + esprima.parse(content, options), + !!optimist.argv['strict-json'] + )); +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/scripts/lib/esprima-master/tools/list-complexity.js b/scripts/lib/esprima-master/tools/list-complexity.js new file mode 100755 index 0000000..4ac64d6 --- /dev/null +++ b/scripts/lib/esprima-master/tools/list-complexity.js @@ -0,0 +1,18 @@ +var cr = require('complexity-report'), + content = require('fs').readFileSync('esprima.js', 'utf-8'), + opt = { logicalor: false, switchcase: false }, + list = []; + +cr.run(content, opt).functions.forEach(function (entry) { + var name = (entry.name === '') ? (':' + entry.line) : entry.name; + list.push({ name: name, value: entry.complexity.cyclomatic }); +}); + +list.sort(function (x, y) { + return y.value - x.value; +}); + +console.log('Most cyclomatic-complex functions:'); +list.slice(0, 6).forEach(function (entry) { + console.log(' ', entry.name, entry.value); +}); diff --git a/scripts/lib/esprima-master/tools/update-coverage.sh b/scripts/lib/esprima-master/tools/update-coverage.sh new file mode 100755 index 0000000..cdaaf84 --- /dev/null +++ b/scripts/lib/esprima-master/tools/update-coverage.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +if [ `command -v istanbul` ]; then + + REVISION=`git log -1 --pretty=%h` + DATE=`git log -1 --pretty=%cD | cut -c 6-16` + + echo "Running coverage analysis..." + istanbul cover test/runner.js + grep -v 'class="path' coverage/lcov-report/esprima/esprima.js.html | grep -v "class='meta" > test/esprima.js.html + +else + echo "Please install Istanbul first!" +fi diff --git a/scripts/lib/estraverse-master/.gitignore b/scripts/lib/estraverse-master/.gitignore new file mode 100755 index 0000000..5b78fb8 --- /dev/null +++ b/scripts/lib/estraverse-master/.gitignore @@ -0,0 +1,14 @@ +# Emacs +*~ +\#*\# + +# Node modules +node_modules/ + +# Cover +.coverage_data/ +cover_html/ +coverage/ + +npm-debug.log +.vimrc.local diff --git a/scripts/lib/estraverse-master/.jshintrc b/scripts/lib/estraverse-master/.jshintrc new file mode 100755 index 0000000..f642dae --- /dev/null +++ b/scripts/lib/estraverse-master/.jshintrc @@ -0,0 +1,16 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "eqnull": true, + "latedef": true, + "noarg": true, + "noempty": true, + "quotmark": "single", + "undef": true, + "unused": true, + "strict": true, + "trailing": true, + + "node": true +} diff --git a/scripts/lib/estraverse-master/.npmignore b/scripts/lib/estraverse-master/.npmignore new file mode 100755 index 0000000..d2db91d --- /dev/null +++ b/scripts/lib/estraverse-master/.npmignore @@ -0,0 +1,15 @@ +npm-debug.log +.DS_Store +.vimrc.local +t.js +.travis.yml +.npmignore +/tmp/ +/.git/ +/node_modules/ +/tools/ +/test/ +/build/ +/cover_html/ +/coverage/ +/.coverage_data/ diff --git a/scripts/lib/estraverse-master/.travis.yml b/scripts/lib/estraverse-master/.travis.yml new file mode 100755 index 0000000..7435fbd --- /dev/null +++ b/scripts/lib/estraverse-master/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" + +matrix: + allow_failures: + - node_js: "0.11" diff --git a/scripts/lib/estraverse-master/LICENSE.BSD b/scripts/lib/estraverse-master/LICENSE.BSD new file mode 100755 index 0000000..3e580c3 --- /dev/null +++ b/scripts/lib/estraverse-master/LICENSE.BSD @@ -0,0 +1,19 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL 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. diff --git a/scripts/lib/estraverse-master/README.md b/scripts/lib/estraverse-master/README.md new file mode 100755 index 0000000..fdef74d --- /dev/null +++ b/scripts/lib/estraverse-master/README.md @@ -0,0 +1,70 @@ +### Estraverse [![Build Status](https://secure.travis-ci.org/Constellation/estraverse.png)](http://travis-ci.org/Constellation/estraverse) + +Estraverse ([estraverse](http://github.com/Constellation/estraverse)) is +[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +traversal functions from [esmangle project](http://github.com/Constellation/esmangle). + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +estraverse.traverse(ast, { + enter: function (node, parent) { + if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') + return estraverse.VisitorOption.Skip; + }, + leave: function (node, parent) { + if (node.type == 'VariableDeclarator') + console.log(node.id.name); + } +}); +``` + +We can use `this.skip` and `this.break` functions instead of using Skip and Break. + +```javascript +estraverse.traverse(ast, { + enter: function (node) { + this.break(); + } +}); +``` + +And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. + +```javascript +result = estraverse.replace(tree, { + enter: function (node) { + // Replace it with replaced. + if (node.type === 'Literal') + return replaced; + } +}); +``` + +### License + +Copyright (C) 2012-2013 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +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 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. diff --git a/scripts/lib/estraverse-master/estraverse.js b/scripts/lib/estraverse-master/estraverse.js new file mode 100755 index 0000000..98ac95f --- /dev/null +++ b/scripts/lib/estraverse-master/estraverse.js @@ -0,0 +1,689 @@ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + 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 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 vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true, define:true*/ +(function (root, factory) { + 'use strict'; + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // and plain browser loading, + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory((root.estraverse = {})); + } +}(this, function (exports) { + 'use strict'; + + var Syntax, + isArray, + VisitorOption, + VisitorKeys, + BREAK, + SKIP; + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + 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', + YieldExpression: 'YieldExpression' + }; + + function ignoreJSHintError() { } + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + ignoreJSHintError(shallowCopy); + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + function lowerBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + i = current + 1; + len -= diff + 1; + } else { + len = diff; + } + } + return i; + } + ignoreJSHintError(lowerBound); + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'defaults', 'rest', 'body'], + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'body', 'superClass'], + ClassExpression: ['id', 'body', 'superClass'], + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'defaults', 'rest', 'body'], + FunctionExpression: ['id', 'params', 'defaults', 'rest', 'body'], + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MethodDefinition: ['key', 'value'], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handlers', 'handler', 'guardedHandlers', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + }; + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = element.wrap || node.type; + candidates = VisitorKeys[nodeType]; + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (!isArray(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + continue; + } + + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if ((nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === candidates[current]) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else { + element = new Element(candidate[current2], [key, current2], null, null); + } + worklist.push(element); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP) { + // replace + element.ref.replace(target); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = element.wrap || node.type; + candidates = VisitorKeys[nodeType]; + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (!isArray(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + continue; + } + + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (nodeType === Syntax.ObjectExpression && 'properties' === candidates[current]) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } + worklist.push(element); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.version = '1.5.1-dev'; + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; +})); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/scripts/lib/estraverse-master/package.json b/scripts/lib/estraverse-master/package.json new file mode 100755 index 0000000..6ec0ed3 --- /dev/null +++ b/scripts/lib/estraverse-master/package.json @@ -0,0 +1,38 @@ +{ + "name": "estraverse", + "description": "ECMAScript JS AST traversal functions", + "homepage": "https://github.com/Constellation/estraverse", + "main": "estraverse.js", + "version": "1.5.1-dev", + "engines": { + "node": ">=0.4.0" + }, + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "http://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/Constellation/estraverse.git" + }, + "devDependencies": { + "mocha": "~1.12.0", + "chai": "~1.7.2", + "jshint": "2.1.5", + "coffee-script": "~1.6.3" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/Constellation/estraverse/raw/master/LICENSE.BSD" + } + ], + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint estraverse.js", + "unit-test": "mocha --compilers coffee:coffee-script" + } +} diff --git a/scripts/lib/estraverse-master/test/controller.coffee b/scripts/lib/estraverse-master/test/controller.coffee new file mode 100755 index 0000000..973f86f --- /dev/null +++ b/scripts/lib/estraverse-master/test/controller.coffee @@ -0,0 +1,60 @@ +# Copyright (C) 2013 Yusuke Suzuki +# +# 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 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. + +'use strict' + +estraverse = require '../' +Dumper = require './dumper' +expect = require('chai').expect + +describe 'controller', -> + it 'traverse', -> + controller = new estraverse.Controller + dumper = new Dumper + tree = + type: 'ObjectExpression' + properties: [{ + key: + type: 'Identifier' + name: 'a' + value: + type: 'Identifier' + name: 'a' + }] + + controller.traverse tree, + enter: (node) -> + dumper.log("enter - #{node.type}") + + leave: (node) -> + dumper.log("leave - #{node.type}") + + expect(Dumper.dump(tree)).to.be.equal """ + enter - ObjectExpression + enter - undefined + enter - Identifier + leave - Identifier + enter - Identifier + leave - Identifier + leave - undefined + leave - ObjectExpression + """ diff --git a/scripts/lib/estraverse-master/test/dumper.coffee b/scripts/lib/estraverse-master/test/dumper.coffee new file mode 100755 index 0000000..c85d21f --- /dev/null +++ b/scripts/lib/estraverse-master/test/dumper.coffee @@ -0,0 +1,47 @@ +# Copyright (C) 2013 Yusuke Suzuki +# +# 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 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. + +'use strict' + +estraverse = require '..' + +module.exports = class Dumper + constructor: -> + @logs = [] + + log: (str) -> + @logs.push str + + result: -> + @logs.join '\n' + + @dump: (tree) -> + dumper = new Dumper + + estraverse.traverse tree, + enter: (node) -> + dumper.log("enter - #{node.type}") + + leave: (node) -> + dumper.log("leave - #{node.type}") + + dumper.result() diff --git a/scripts/lib/estraverse-master/test/traverse.coffee b/scripts/lib/estraverse-master/test/traverse.coffee new file mode 100755 index 0000000..00c1a4a --- /dev/null +++ b/scripts/lib/estraverse-master/test/traverse.coffee @@ -0,0 +1,270 @@ +# Copyright (C) 2013 Yusuke Suzuki +# +# 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 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. + +'use strict' + +Dumper = require './dumper' +expect = require('chai').expect + +describe 'object expression', -> + it 'properties', -> + tree = + type: 'ObjectExpression' + properties: [{ + type: 'Property' + key: + type: 'Identifier' + name: 'a' + value: + type: 'Identifier' + name: 'a' + }] + + expect(Dumper.dump(tree)).to.be.equal """ + enter - ObjectExpression + enter - Property + enter - Identifier + leave - Identifier + enter - Identifier + leave - Identifier + leave - Property + leave - ObjectExpression + """ + + it 'properties without type', -> + tree = + type: 'ObjectExpression' + properties: [{ + key: + type: 'Identifier' + name: 'a' + value: + type: 'Identifier' + name: 'a' + }] + + expect(Dumper.dump(tree)).to.be.equal """ + enter - ObjectExpression + enter - undefined + enter - Identifier + leave - Identifier + enter - Identifier + leave - Identifier + leave - undefined + leave - ObjectExpression + """ + +describe 'object pattern', -> + it 'properties', -> + tree = + type: 'ObjectPattern' + properties: [{ + type: 'Property' + key: + type: 'Identifier' + name: 'a' + value: + type: 'Identifier' + name: 'a' + }] + + expect(Dumper.dump(tree)).to.be.equal """ + enter - ObjectPattern + enter - Property + enter - Identifier + leave - Identifier + enter - Identifier + leave - Identifier + leave - Property + leave - ObjectPattern + """ + + it 'properties without type', -> + tree = + type: 'ObjectPattern' + properties: [{ + key: + type: 'Identifier' + name: 'a' + value: + type: 'Identifier' + name: 'a' + }] + + expect(Dumper.dump(tree)).to.be.equal """ + enter - ObjectPattern + enter - undefined + enter - Identifier + leave - Identifier + enter - Identifier + leave - Identifier + leave - undefined + leave - ObjectPattern + """ + +describe 'try statement', -> + it 'old interface', -> + tree = + type: 'TryStatement' + handlers: [{ + type: 'BlockStatement' + body: [] + }] + finalizer: + type: 'BlockStatement' + body: [] + + expect(Dumper.dump(tree)).to.be.equal """ + enter - TryStatement + enter - BlockStatement + leave - BlockStatement + enter - BlockStatement + leave - BlockStatement + leave - TryStatement + """ + + it 'new interface', -> + tree = + type: 'TryStatement' + handler: [{ + type: 'BlockStatement' + body: [] + }] + guardedHandlers: null + finalizer: + type: 'BlockStatement' + body: [] + + expect(Dumper.dump(tree)).to.be.equal """ + enter - TryStatement + enter - BlockStatement + leave - BlockStatement + enter - BlockStatement + leave - BlockStatement + leave - TryStatement + """ + +describe 'arrow function expression', -> + it 'traverse', -> + tree = + type: 'ArrowFunctionExpression' + params: [{ + type: 'Identifier' + name: 'a' + }] + defaults: [{ + type: 'Literal' + value: 20 + }] + rest: { + type: 'Identifier' + name: 'rest' + } + body: + type: 'BlockStatement' + body: [] + + expect(Dumper.dump(tree)).to.be.equal """ + enter - ArrowFunctionExpression + enter - Identifier + leave - Identifier + enter - Literal + leave - Literal + enter - Identifier + leave - Identifier + enter - BlockStatement + leave - BlockStatement + leave - ArrowFunctionExpression + """ + +describe 'function expression', -> + it 'traverse', -> + tree = + type: 'FunctionExpression' + params: [{ + type: 'Identifier' + name: 'a' + }] + defaults: [{ + type: 'Literal' + value: 20 + }] + rest: { + type: 'Identifier' + name: 'rest' + } + body: + type: 'BlockStatement' + body: [] + + expect(Dumper.dump(tree)).to.be.equal """ + enter - FunctionExpression + enter - Identifier + leave - Identifier + enter - Literal + leave - Literal + enter - Identifier + leave - Identifier + enter - BlockStatement + leave - BlockStatement + leave - FunctionExpression + """ + +describe 'function declaration', -> + it 'traverse', -> + tree = + type: 'FunctionDeclaration' + id: { + type: 'Identifier' + name: 'decl' + } + params: [{ + type: 'Identifier' + name: 'a' + }] + defaults: [{ + type: 'Literal' + value: 20 + }] + rest: { + type: 'Identifier' + name: 'rest' + } + body: + type: 'BlockStatement' + body: [] + + expect(Dumper.dump(tree)).to.be.equal """ + enter - FunctionDeclaration + enter - Identifier + leave - Identifier + enter - Identifier + leave - Identifier + enter - Literal + leave - Literal + enter - Identifier + leave - Identifier + enter - BlockStatement + leave - BlockStatement + leave - FunctionDeclaration + """ + diff --git a/scripts/lib/require.js b/scripts/lib/require.js new file mode 100644 index 0000000..e599a6a --- /dev/null +++ b/scripts/lib/require.js @@ -0,0 +1,36 @@ +/* + RequireJS 2.1.11 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. + Available via the MIT or new BSD license. + see: http://github.com/jrburke/requirejs for details +*/ +var requirejs,require,define; +(function(ca){function G(b){return"[object Function]"===M.call(b)}function H(b){return"[object Array]"===M.call(b)}function v(b,c){if(b){var d;for(d=0;dthis.depCount&&!this.defined){if(G(c)){if(this.events.error&&this.map.isDefine||h.onError!==da)try{f=i.execCb(b,c,e,f)}catch(d){a=d}else f=i.execCb(b,c,e,f);this.map.isDefine&&void 0===f&&((e=this.module)?f=e.exports:this.usingExports&& +(f=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else f=c;this.exports=f;if(this.map.isDefine&&!this.ignore&&(p[b]=f,h.onResourceLoad))h.onResourceLoad(i,this.map,this.depMaps);y(b);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a= +this.map,b=a.id,d=m(a.prefix);this.depMaps.push(d);r(d,"defined",t(this,function(f){var d,g;g=j(ba,this.map.id);var J=this.map.name,u=this.map.parentMap?this.map.parentMap.name:null,p=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(J=f.normalize(J,function(a){return c(a,u,!0)})||""),f=m(a.prefix+"!"+J,this.map.parentMap),r(f,"defined",t(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),g=j(k,f.id)){this.depMaps.push(f); +if(this.events.error)g.on("error",t(this,function(a){this.emit("error",a)}));g.enable()}}else g?(this.map.url=i.nameToUrl(g),this.load()):(d=t(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),d.error=t(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];B(k,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),d.fromText=t(this,function(f,c){var g=a.name,J=m(g),k=O;c&&(f=c);k&&(O=!1);q(J);s(l.config,b)&&(l.config[g]=l.config[b]);try{h.exec(f)}catch(j){return w(C("fromtexteval", +"fromText eval for "+b+" failed: "+j,j,[b]))}k&&(O=!0);this.depMaps.push(J);i.completeLoad(g);p([g],d)}),f.load(a.name,p,d,l))}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){W[this.map.id]=this;this.enabling=this.enabled=!0;v(this.depMaps,t(this,function(a,b){var c,f;if("string"===typeof a){a=m(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=j(N,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;r(a,"defined",t(this,function(a){this.defineDep(b, +a);this.check()}));this.errback&&r(a,"error",t(this,this.errback))}c=a.id;f=k[c];!s(N,c)&&(f&&!f.enabled)&&i.enable(a,this)}));B(this.pluginMaps,t(this,function(a){var b=j(k,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){v(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:l,contextName:b,registry:k,defined:p,urlFetched:T,defQueue:A,Module:$,makeModuleMap:m, +nextTick:h.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=l.shim,c={paths:!0,bundles:!0,config:!0,map:!0};B(a,function(a,b){c[b]?(l[b]||(l[b]={}),V(l[b],a,!0,!0)):l[b]=a});a.bundles&&B(a.bundles,function(a,b){v(a,function(a){a!==b&&(ba[a]=b)})});a.shim&&(B(a.shim,function(a,c){H(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);b[c]=a}),l.shim=b);a.packages&&v(a.packages,function(a){var b, +a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(l.paths[b]=a.location);l.pkgs[b]=a.name+"/"+(a.main||"main").replace(ja,"").replace(R,"")});B(k,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=m(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ca,arguments));return b||a.exports&&ea(a.exports)}},makeRequire:function(a,e){function g(f,c,d){var j,l;e.enableBuildCallback&&(c&&G(c))&&(c.__requireJsBuild= +!0);if("string"===typeof f){if(G(c))return w(C("requireargs","Invalid require call"),d);if(a&&s(N,f))return N[f](k[a.id]);if(h.get)return h.get(i,f,a,g);j=m(f,a,!1,!0);j=j.id;return!s(p,j)?w(C("notloaded",'Module name "'+j+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):p[j]}L();i.nextTick(function(){L();l=q(m(null,a));l.skipMap=e.skipMap;l.init(f,c,d,{enabled:!0});D()});return g}e=e||{};V(g,{isBrowser:z,toUrl:function(b){var e,d=b.lastIndexOf("."),g=b.split("/")[0];if(-1!== +d&&(!("."===g||".."===g)||1g.attachEvent.toString().indexOf("[native code"))&&!Z?(O=!0,g.attachEvent("onreadystatechange",b.onScriptLoad)): +(g.addEventListener("load",b.onScriptLoad,!1),g.addEventListener("error",b.onScriptError,!1)),g.src=d,L=g,D?y.insertBefore(g,D):y.appendChild(g),L=null,g;if(fa)try{importScripts(d),b.completeLoad(c)}catch(j){b.onError(C("importscripts","importScripts failed for "+c+" at "+d,j,[c]))}};z&&!r.skipDataMain&&U(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(K=b.getAttribute("data-main"))return q=K,r.baseUrl||(E=q.split("/"),q=E.pop(),Q=E.length?E.join("/")+"/":"./",r.baseUrl= +Q),q=q.replace(R,""),h.jsExtRegExp.test(q)&&(q=K),r.deps=r.deps?r.deps.concat(q):[q],!0});define=function(b,c,d){var g,h;"string"!==typeof b&&(d=c,c=b,b=null);H(c)||(d=c,c=null);!c&&G(d)&&(c=[],d.length&&(d.toString().replace(la,"").replace(ma,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(O){if(!(g=L))P&&"interactive"===P.readyState||U(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return P=b}),g=P;g&&(b|| +(b=g.getAttribute("data-requiremodule")),h=F[g.getAttribute("data-requirecontext")])}(h?h.defQueue:S).push([b,c,d])};define.amd={jQuery:!0};h.exec=function(b){return eval(b)};h(r)}})(this); diff --git a/scripts/lib/underscore-min.js b/scripts/lib/underscore-min.js new file mode 100644 index 0000000..d22f881 --- /dev/null +++ b/scripts/lib/underscore-min.js @@ -0,0 +1,6 @@ +// Underscore.js 1.5.2 +// http://underscorejs.org +// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. +(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,g=e.filter,d=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,w=Object.keys,_=i.bind,j=function(n){return n instanceof j?n:this instanceof j?(this._wrapped=n,void 0):new j(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=j),exports._=j):n._=j,j.VERSION="1.5.2";var A=j.each=j.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a=j.keys(n),u=0,i=a.length;i>u;u++)if(t.call(e,n[a[u]],a[u],n)===r)return};j.map=j.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e.push(t.call(r,n,u,i))}),e)};var E="Reduce of empty array with no initial value";j.reduce=j.foldl=j.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=j.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(E);return r},j.reduceRight=j.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=j.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=j.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(E);return r},j.find=j.detect=function(n,t,r){var e;return O(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},j.filter=j.select=function(n,t,r){var e=[];return null==n?e:g&&n.filter===g?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&e.push(n)}),e)},j.reject=function(n,t,r){return j.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},j.every=j.all=function(n,t,e){t||(t=j.identity);var u=!0;return null==n?u:d&&n.every===d?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var O=j.some=j.any=function(n,t,e){t||(t=j.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};j.contains=j.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:O(n,function(n){return n===t})},j.invoke=function(n,t){var r=o.call(arguments,2),e=j.isFunction(t);return j.map(n,function(n){return(e?t:n[t]).apply(n,r)})},j.pluck=function(n,t){return j.map(n,function(n){return n[t]})},j.where=function(n,t,r){return j.isEmpty(t)?r?void 0:[]:j[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},j.findWhere=function(n,t){return j.where(n,t,!0)},j.max=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.max.apply(Math,n);if(!t&&j.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>e.computed&&(e={value:n,computed:a})}),e.value},j.min=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.min.apply(Math,n);if(!t&&j.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;ae||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={},i=null==r?j.identity:k(r);return A(t,function(r,a){var o=i.call(e,r,a,t);n(u,o,r)}),u}};j.groupBy=F(function(n,t,r){(j.has(n,t)?n[t]:n[t]=[]).push(r)}),j.indexBy=F(function(n,t,r){n[t]=r}),j.countBy=F(function(n,t){j.has(n,t)?n[t]++:n[t]=1}),j.sortedIndex=function(n,t,r,e){r=null==r?j.identity:k(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;r.call(e,n[o])=0})})},j.difference=function(n){var t=c.apply(e,o.call(arguments,1));return j.filter(n,function(n){return!j.contains(t,n)})},j.zip=function(){for(var n=j.max(j.pluck(arguments,"length").concat(0)),t=new Array(n),r=0;n>r;r++)t[r]=j.pluck(arguments,""+r);return t},j.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},j.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=j.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},j.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},j.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=new Array(e);e>u;)i[u++]=n,n+=r;return i};var R=function(){};j.bind=function(n,t){var r,e;if(_&&n.bind===_)return _.apply(n,o.call(arguments,1));if(!j.isFunction(n))throw new TypeError;return r=o.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(o.call(arguments)));R.prototype=n.prototype;var u=new R;R.prototype=null;var i=n.apply(u,r.concat(o.call(arguments)));return Object(i)===i?i:u}},j.partial=function(n){var t=o.call(arguments,1);return function(){return n.apply(this,t.concat(o.call(arguments)))}},j.bindAll=function(n){var t=o.call(arguments,1);if(0===t.length)throw new Error("bindAll must be passed function names");return A(t,function(t){n[t]=j.bind(n[t],n)}),n},j.memoize=function(n,t){var r={};return t||(t=j.identity),function(){var e=t.apply(this,arguments);return j.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},j.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},j.defer=function(n){return j.delay.apply(j,[n,1].concat(o.call(arguments,1)))},j.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var c=function(){o=r.leading===!1?0:new Date,a=null,i=n.apply(e,u)};return function(){var l=new Date;o||r.leading!==!1||(o=l);var f=t-(l-o);return e=this,u=arguments,0>=f?(clearTimeout(a),a=null,o=l,i=n.apply(e,u)):a||r.trailing===!1||(a=setTimeout(c,f)),i}},j.debounce=function(n,t,r){var e,u,i,a,o;return function(){i=this,u=arguments,a=new Date;var c=function(){var l=new Date-a;t>l?e=setTimeout(c,t-l):(e=null,r||(o=n.apply(i,u)))},l=r&&!e;return e||(e=setTimeout(c,t)),l&&(o=n.apply(i,u)),o}},j.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},j.wrap=function(n,t){return function(){var r=[n];return a.apply(r,arguments),t.apply(this,r)}},j.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},j.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},j.keys=w||function(n){if(n!==Object(n))throw new TypeError("Invalid object");var t=[];for(var r in n)j.has(n,r)&&t.push(r);return t},j.values=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},j.pairs=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},j.invert=function(n){for(var t={},r=j.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},j.functions=j.methods=function(n){var t=[];for(var r in n)j.isFunction(n[r])&&t.push(r);return t.sort()},j.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},j.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},j.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)j.contains(r,u)||(t[u]=n[u]);return t},j.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]===void 0&&(n[r]=t[r])}),n},j.clone=function(n){return j.isObject(n)?j.isArray(n)?n.slice():j.extend({},n):n},j.tap=function(n,t){return t(n),n};var S=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof j&&(n=n._wrapped),t instanceof j&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==String(t);case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;var a=n.constructor,o=t.constructor;if(a!==o&&!(j.isFunction(a)&&a instanceof a&&j.isFunction(o)&&o instanceof o))return!1;r.push(n),e.push(t);var c=0,f=!0;if("[object Array]"==u){if(c=n.length,f=c==t.length)for(;c--&&(f=S(n[c],t[c],r,e)););}else{for(var s in n)if(j.has(n,s)&&(c++,!(f=j.has(t,s)&&S(n[s],t[s],r,e))))break;if(f){for(s in t)if(j.has(t,s)&&!c--)break;f=!c}}return r.pop(),e.pop(),f};j.isEqual=function(n,t){return S(n,t,[],[])},j.isEmpty=function(n){if(null==n)return!0;if(j.isArray(n)||j.isString(n))return 0===n.length;for(var t in n)if(j.has(n,t))return!1;return!0},j.isElement=function(n){return!(!n||1!==n.nodeType)},j.isArray=x||function(n){return"[object Array]"==l.call(n)},j.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){j["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),j.isArguments(arguments)||(j.isArguments=function(n){return!(!n||!j.has(n,"callee"))}),"function"!=typeof/./&&(j.isFunction=function(n){return"function"==typeof n}),j.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},j.isNaN=function(n){return j.isNumber(n)&&n!=+n},j.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},j.isNull=function(n){return null===n},j.isUndefined=function(n){return n===void 0},j.has=function(n,t){return f.call(n,t)},j.noConflict=function(){return n._=t,this},j.identity=function(n){return n},j.times=function(n,t,r){for(var e=Array(Math.max(0,n)),u=0;n>u;u++)e[u]=t.call(r,u);return e},j.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))};var I={escape:{"&":"&","<":"<",">":">",'"':""","'":"'"}};I.unescape=j.invert(I.escape);var T={escape:new RegExp("["+j.keys(I.escape).join("")+"]","g"),unescape:new RegExp("("+j.keys(I.unescape).join("|")+")","g")};j.each(["escape","unescape"],function(n){j[n]=function(t){return null==t?"":(""+t).replace(T[n],function(t){return I[n][t]})}}),j.result=function(n,t){if(null==n)return void 0;var r=n[t];return j.isFunction(r)?r.call(n):r},j.mixin=function(n){A(j.functions(n),function(t){var r=j[t]=n[t];j.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),z.call(this,r.apply(j,n))}})};var N=0;j.uniqueId=function(n){var t=++N+"";return n?n+t:t},j.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var q=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\t|\u2028|\u2029/g;j.template=function(n,t,r){var e;r=j.defaults({},r,j.templateSettings);var u=new RegExp([(r.escape||q).source,(r.interpolate||q).source,(r.evaluate||q).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(D,function(n){return"\\"+B[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=new Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,j);var c=function(n){return e.call(this,n,j)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},j.chain=function(n){return j(n).chain()};var z=function(n){return this._chain?j(n).chain():n};j.mixin(j),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];j.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],z.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];j.prototype[n]=function(){return z.call(this,t.apply(this._wrapped,arguments))}}),j.extend(j.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this); +//# sourceMappingURL=underscore-min.map \ No newline at end of file diff --git a/scripts/main.js b/scripts/main.js new file mode 100644 index 0000000..4643fdb --- /dev/null +++ b/scripts/main.js @@ -0,0 +1,105 @@ +/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ +/*global define, require, document*/ + +require.config({ + paths: { + underscore: 'lib/underscore-min', + }, + shim: { + "underscore": { + exports: "_" + } + } +}); + +require(["lib/esprima-master/esprima", "lib/estraverse-master/estraverse", "annotate", "text!testDummy.js", "underscore"], function (esprima, estraverse, annotate, testDummy, _) { + // get the ast + var ast = esprima.parse(testDummy, { + tolerant: true, + attachComment: true, + loc: true, + range: true + }); + + var outputLength = 0; + var output = testDummy; + + // set some imaginary cursor position + var cursor = { + line: 6, + column: 43 + }; + + document.getElementById("input").innerHTML = testDummy; + + // traverse the ast + estraverse.traverse(ast, { + enter: enter, + //leave: leave + }); + + document.getElementById("output").innerHTML = output; + + function enter(node, parent) { + // Check if node is annotatable and if so, call it's anotation function + var jsDoc; + if (isAnnotatable(node)) { + // Create jsDoc annotation + jsDoc = annotate[node.type](node, parent); + + // Check if there is already a jsdoc annotation for this annnotatable + var jsDocCommentExists = false; + _.forEach(node.leadingComments, function(value, key){ + if(value.type === "Block" && value.value.charAt(0) === "*"){ + // jsDoc comment + jsDocCommentExists = true; + } + }); + + // Insert jsDoc into output variable + if(_.isString(jsDoc) && !jsDocCommentExists){ + output = output.substr(0, node.range[0]+outputLength) + jsDoc + output.substr(node.range[0]+outputLength); + outputLength += jsDoc.length; + } + } + } + + /*function leave(node, parent) { + //console.log(node.id); + };*/ + + + /** + * Description + * @param {object} Check if node is annotatable + */ + function isAnnotatable(node) { + // Annotatable elements + var ANNOTATABLES = [ + esprima.Syntax.ExpressionStatement, + esprima.Syntax.VariableDeclaration, + esprima.Syntax.FunctionDeclaration, + esprima.Syntax.Property + ]; // That's it for the timebeeing + if (ANNOTATABLES.indexOf(node.type) != -1) { + return true; + } else { + return false; + } + } + + /** + * Compare two positions + * @param {type} a first position + * @param {type} b second position + */ + function positionAGreaterB(a, b) { + if (a.line > b.line) { + return true; + } else if (a.line === b.line && a.column > b.column) { + return true; + } else { + return false; + } + } +}); \ No newline at end of file diff --git a/scripts/testDummy.js b/scripts/testDummy.js new file mode 100644 index 0000000..1400f4b --- /dev/null +++ b/scripts/testDummy.js @@ -0,0 +1,70 @@ +/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */ +/*global define, $, brackets, window */ + +/** This file is only used to be tested against annotate */ +define(function (require, exports, module) { + + 'use strict'; + + var num1 = 1; + var greetings = "Hello world"; + var GREETINGS = "Hello world"; + var _GREETINGS = "Hello world"; + + var variable1, variable2, _variable3, VARIABLE4; + + /* + * educated guess, but no js doc + */ + function declaration(input) { + + var content = "stuff"; + } + + //* fake jsdoc * + var expression = function(p1, p2) { + + var content = "stuff"; + + }; + + /** inline jsDoc */ + function noParams() { + + return null; + + } + + + var _privateStuff = function(p1, p2) { + var content = "I start with an underscore"; + return content; + }; + + + var myObject = {}; + + myObject.myFunction = function (param1, param2, param3) { + + }; + + + myObject.prototype.myFunction = function (param1, param2) { + + }; + + + var a = { + doA: function(param1, param2){ + var content = "stuff"; + + return content; + }, + doB: function(param1, param2){ + var content = "stuff"; + + return content; + } + }; + +}); \ No newline at end of file diff --git a/scripts/text.js b/scripts/text.js new file mode 100644 index 0000000..1e4fc96 --- /dev/null +++ b/scripts/text.js @@ -0,0 +1,386 @@ +/** + * @license RequireJS text 2.0.10 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/requirejs/text for details + */ +/*jslint regexp: true */ +/*global require, XMLHttpRequest, ActiveXObject, + define, window, process, Packages, + java, location, Components, FileUtils */ + +define(['module'], function (module) { + 'use strict'; + + var text, fs, Cc, Ci, xpcIsWindows, + progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], + xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, + bodyRegExp = /]*>\s*([\s\S]+)\s*<\/body>/im, + hasLocation = typeof location !== 'undefined' && location.href, + defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''), + defaultHostName = hasLocation && location.hostname, + defaultPort = hasLocation && (location.port || undefined), + buildMap = {}, + masterConfig = (module.config && module.config()) || {}; + + text = { + version: '2.0.10', + + strip: function (content) { + //Strips declarations so that external SVG and XML + //documents can be added to a document without worry. Also, if the string + //is an HTML document, only the part inside the body tag is returned. + if (content) { + content = content.replace(xmlRegExp, ""); + var matches = content.match(bodyRegExp); + if (matches) { + content = matches[1]; + } + } else { + content = ""; + } + return content; + }, + + jsEscape: function (content) { + return content.replace(/(['\\])/g, '\\$1') + .replace(/[\f]/g, "\\f") + .replace(/[\b]/g, "\\b") + .replace(/[\n]/g, "\\n") + .replace(/[\t]/g, "\\t") + .replace(/[\r]/g, "\\r") + .replace(/[\u2028]/g, "\\u2028") + .replace(/[\u2029]/g, "\\u2029"); + }, + + createXhr: masterConfig.createXhr || function () { + //Would love to dump the ActiveX crap in here. Need IE 6 to die first. + var xhr, i, progId; + if (typeof XMLHttpRequest !== "undefined") { + return new XMLHttpRequest(); + } else if (typeof ActiveXObject !== "undefined") { + for (i = 0; i < 3; i += 1) { + progId = progIds[i]; + try { + xhr = new ActiveXObject(progId); + } catch (e) {} + + if (xhr) { + progIds = [progId]; // so faster next time + break; + } + } + } + + return xhr; + }, + + /** + * Parses a resource name into its component parts. Resource names + * look like: module/name.ext!strip, where the !strip part is + * optional. + * @param {String} name the resource name + * @returns {Object} with properties "moduleName", "ext" and "strip" + * where strip is a boolean. + */ + parseName: function (name) { + var modName, ext, temp, + strip = false, + index = name.indexOf("."), + isRelative = name.indexOf('./') === 0 || + name.indexOf('../') === 0; + + if (index !== -1 && (!isRelative || index > 1)) { + modName = name.substring(0, index); + ext = name.substring(index + 1, name.length); + } else { + modName = name; + } + + temp = ext || modName; + index = temp.indexOf("!"); + if (index !== -1) { + //Pull off the strip arg. + strip = temp.substring(index + 1) === "strip"; + temp = temp.substring(0, index); + if (ext) { + ext = temp; + } else { + modName = temp; + } + } + + return { + moduleName: modName, + ext: ext, + strip: strip + }; + }, + + xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/, + + /** + * Is an URL on another domain. Only works for browser use, returns + * false in non-browser environments. Only used to know if an + * optimized .js version of a text resource should be loaded + * instead. + * @param {String} url + * @returns Boolean + */ + useXhr: function (url, protocol, hostname, port) { + var uProtocol, uHostName, uPort, + match = text.xdRegExp.exec(url); + if (!match) { + return true; + } + uProtocol = match[2]; + uHostName = match[3]; + + uHostName = uHostName.split(':'); + uPort = uHostName[1]; + uHostName = uHostName[0]; + + return (!uProtocol || uProtocol === protocol) && + (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) && + ((!uPort && !uHostName) || uPort === port); + }, + + finishLoad: function (name, strip, content, onLoad) { + content = strip ? text.strip(content) : content; + if (masterConfig.isBuild) { + buildMap[name] = content; + } + onLoad(content); + }, + + load: function (name, req, onLoad, config) { + //Name has format: some.module.filext!strip + //The strip part is optional. + //if strip is present, then that means only get the string contents + //inside a body tag in an HTML string. For XML/SVG content it means + //removing the declarations so the content can be inserted + //into the current doc without problems. + + // Do not bother with the work if a build and text will + // not be inlined. + if (config.isBuild && !config.inlineText) { + onLoad(); + return; + } + + masterConfig.isBuild = config.isBuild; + + var parsed = text.parseName(name), + nonStripName = parsed.moduleName + + (parsed.ext ? '.' + parsed.ext : ''), + url = req.toUrl(nonStripName), + useXhr = (masterConfig.useXhr) || + text.useXhr; + + // Do not load if it is an empty: url + if (url.indexOf('empty:') === 0) { + onLoad(); + return; + } + + //Load the text. Use XHR if possible and in a browser. + if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) { + text.get(url, function (content) { + text.finishLoad(name, parsed.strip, content, onLoad); + }, function (err) { + if (onLoad.error) { + onLoad.error(err); + } + }); + } else { + //Need to fetch the resource across domains. Assume + //the resource has been optimized into a JS module. Fetch + //by the module name + extension, but do not include the + //!strip part to avoid file system issues. + req([nonStripName], function (content) { + text.finishLoad(parsed.moduleName + '.' + parsed.ext, + parsed.strip, content, onLoad); + }); + } + }, + + write: function (pluginName, moduleName, write, config) { + if (buildMap.hasOwnProperty(moduleName)) { + var content = text.jsEscape(buildMap[moduleName]); + write.asModule(pluginName + "!" + moduleName, + "define(function () { return '" + + content + + "';});\n"); + } + }, + + writeFile: function (pluginName, moduleName, req, write, config) { + var parsed = text.parseName(moduleName), + extPart = parsed.ext ? '.' + parsed.ext : '', + nonStripName = parsed.moduleName + extPart, + //Use a '.js' file name so that it indicates it is a + //script that can be loaded across domains. + fileName = req.toUrl(parsed.moduleName + extPart) + '.js'; + + //Leverage own load() method to load plugin value, but only + //write out values that do not have the strip argument, + //to avoid any potential issues with ! in file names. + text.load(nonStripName, req, function (value) { + //Use own write() method to construct full module value. + //But need to create shell that translates writeFile's + //write() to the right interface. + var textWrite = function (contents) { + return write(fileName, contents); + }; + textWrite.asModule = function (moduleName, contents) { + return write.asModule(moduleName, fileName, contents); + }; + + text.write(pluginName, nonStripName, textWrite, config); + }, config); + } + }; + + if (masterConfig.env === 'node' || (!masterConfig.env && + typeof process !== "undefined" && + process.versions && + !!process.versions.node && + !process.versions['node-webkit'])) { + //Using special require.nodeRequire, something added by r.js. + fs = require.nodeRequire('fs'); + + text.get = function (url, callback, errback) { + try { + var file = fs.readFileSync(url, 'utf8'); + //Remove BOM (Byte Mark Order) from utf8 files if it is there. + if (file.indexOf('\uFEFF') === 0) { + file = file.substring(1); + } + callback(file); + } catch (e) { + errback(e); + } + }; + } else if (masterConfig.env === 'xhr' || (!masterConfig.env && + text.createXhr())) { + text.get = function (url, callback, errback, headers) { + var xhr = text.createXhr(), header; + xhr.open('GET', url, true); + + //Allow plugins direct access to xhr headers + if (headers) { + for (header in headers) { + if (headers.hasOwnProperty(header)) { + xhr.setRequestHeader(header.toLowerCase(), headers[header]); + } + } + } + + //Allow overrides specified in config + if (masterConfig.onXhr) { + masterConfig.onXhr(xhr, url); + } + + xhr.onreadystatechange = function (evt) { + var status, err; + //Do not explicitly handle errors, those should be + //visible via console output in the browser. + if (xhr.readyState === 4) { + status = xhr.status; + if (status > 399 && status < 600) { + //An http 4xx or 5xx error. Signal an error. + err = new Error(url + ' HTTP status: ' + status); + err.xhr = xhr; + errback(err); + } else { + callback(xhr.responseText); + } + + if (masterConfig.onXhrComplete) { + masterConfig.onXhrComplete(xhr, url); + } + } + }; + xhr.send(null); + }; + } else if (masterConfig.env === 'rhino' || (!masterConfig.env && + typeof Packages !== 'undefined' && typeof java !== 'undefined')) { + //Why Java, why is this so awkward? + text.get = function (url, callback) { + var stringBuffer, line, + encoding = "utf-8", + file = new java.io.File(url), + lineSeparator = java.lang.System.getProperty("line.separator"), + input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), + content = ''; + try { + stringBuffer = new java.lang.StringBuffer(); + line = input.readLine(); + + // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 + // http://www.unicode.org/faq/utf_bom.html + + // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: + // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 + if (line && line.length() && line.charAt(0) === 0xfeff) { + // Eat the BOM, since we've already found the encoding on this file, + // and we plan to concatenating this buffer with others; the BOM should + // only appear at the top of a file. + line = line.substring(1); + } + + if (line !== null) { + stringBuffer.append(line); + } + + while ((line = input.readLine()) !== null) { + stringBuffer.append(lineSeparator); + stringBuffer.append(line); + } + //Make sure we return a JavaScript string and not a Java string. + content = String(stringBuffer.toString()); //String + } finally { + input.close(); + } + callback(content); + }; + } else if (masterConfig.env === 'xpconnect' || (!masterConfig.env && + typeof Components !== 'undefined' && Components.classes && + Components.interfaces)) { + //Avert your gaze! + Cc = Components.classes, + Ci = Components.interfaces; + Components.utils['import']('resource://gre/modules/FileUtils.jsm'); + xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc); + + text.get = function (url, callback) { + var inStream, convertStream, fileObj, + readData = {}; + + if (xpcIsWindows) { + url = url.replace(/\//g, '\\'); + } + + fileObj = new FileUtils.File(url); + + //XPCOM, you so crazy + try { + inStream = Cc['@mozilla.org/network/file-input-stream;1'] + .createInstance(Ci.nsIFileInputStream); + inStream.init(fileObj, 1, 0, false); + + convertStream = Cc['@mozilla.org/intl/converter-input-stream;1'] + .createInstance(Ci.nsIConverterInputStream); + convertStream.init(inStream, "utf-8", inStream.available(), + Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); + + convertStream.readString(inStream.available(), readData); + convertStream.close(); + inStream.close(); + callback(readData.value); + } catch (e) { + throw new Error((fileObj && fileObj.path || '') + ': ' + e); + } + }; + } + return text; +});