Debian Codegraph @

extensions/CodeEditor/modules/lib/ace/worker-lua.js

raw symbols SCIP
1 "no use strict";
2 !(function(window) {
3 if (typeof window.window != "undefined" && window.document)
4 return;
5 if (window.require && window.define)
6 return;
7
8 if (!window.console) {
9 window.console = function() {
10 var msgs = Array.prototype.slice.call(arguments, 0);
11 postMessage({type: "log", data: msgs});
12 };
13 window.console.error =
14 window.console.warn =
15 window.console.log =
16 window.console.trace = window.console;
17 }
18 window.window = window;
19 window.ace = window;
20
21 window.onerror = function(message, file, line, col, err) {
22 postMessage({type: "error", data: {
23 message: message,
24 data: err && err.data,
25 file: file,
26 line: line,
27 col: col,
28 stack: err && err.stack
29 }});
30 };
31
32 window.normalizeModule = function(parentId, moduleName) {
33 // normalize plugin requires
34 if (moduleName.indexOf("!") !== -1) {
35 var chunks = moduleName.split("!");
36 return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]);
37 }
38 // normalize relative requires
39 if (moduleName.charAt(0) == ".") {
40 var base = parentId.split("/").slice(0, -1).join("/");
41 moduleName = (base ? base + "/" : "") + moduleName;
42
43 while (moduleName.indexOf(".") !== -1 && previous != moduleName) {
44 var previous = moduleName;
45 moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
46 }
47 }
48
49 return moduleName;
50 };
51
52 window.require = function require(parentId, id) {
53 if (!id) {
54 id = parentId;
55 parentId = null;
56 }
57 if (!id.charAt)
58 throw new Error("worker.js require() accepts only (parentId, id) as arguments");
59
60 id = window.normalizeModule(parentId, id);
61
62 var module = window.require.modules[id];
63 if (module) {
64 if (!module.initialized) {
65 module.initialized = true;
66 module.exports = module.factory().exports;
67 }
68 return module.exports;
69 }
70
71 if (!window.require.tlns)
72 return console.log("unable to load " + id);
73
74 var path = resolveModuleId(id, window.require.tlns);
75 if (path.slice(-3) != ".js") path += ".js";
76
77 window.require.id = id;
78 window.require.modules[id] = {}; // prevent infinite loop on broken modules
79 importScripts(path);
80 return window.require(parentId, id);
81 };
82 function resolveModuleId(id, paths) {
83 var testPath = id, tail = "";
84 while (testPath) {
85 var alias = paths[testPath];
86 if (typeof alias == "string") {
87 return alias + tail;
88 } else if (alias) {
89 return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name);
90 } else if (alias === false) {
91 return "";
92 }
93 var i = testPath.lastIndexOf("/");
94 if (i === -1) break;
95 tail = testPath.substr(i) + tail;
96 testPath = testPath.slice(0, i);
97 }
98 return id;
99 }
100 window.require.modules = {};
101 window.require.tlns = {};
102
103 window.define = function(id, deps, factory) {
104 if (arguments.length == 2) {
105 factory = deps;
106 if (typeof id != "string") {
107 deps = id;
108 id = window.require.id;
109 }
110 } else if (arguments.length == 1) {
111 factory = id;
112 deps = [];
113 id = window.require.id;
114 }
115
116 if (typeof factory != "function") {
117 window.require.modules[id] = {
118 exports: factory,
119 initialized: true
120 };
121 return;
122 }
123
124 if (!deps.length)
125 // If there is no dependencies, we inject "require", "exports" and
126 // "module" as dependencies, to provide CommonJS compatibility.
127 deps = ["require", "exports", "module"];
128
129 var req = function(childId) {
130 return window.require(id, childId);
131 };
132
133 window.require.modules[id] = {
134 exports: {},
135 factory: function() {
136 var module = this;
137 var returnExports = factory.apply(this, deps.slice(0, factory.length).map(function(dep) {
138 switch (dep) {
139 // Because "require", "exports" and "module" aren't actual
140 // dependencies, we must handle them seperately.
141 case "require": return req;
142 case "exports": return module.exports;
143 case "module": return module;
144 // But for all other dependencies, we can just go ahead and
145 // require them.
146 default: return req(dep);
147 }
148 }));
149 if (returnExports)
150 module.exports = returnExports;
151 return module;
152 }
153 };
154 };
155 window.define.amd = {};
156 window.require.tlns = {};
157 window.initBaseUrls = function initBaseUrls(topLevelNamespaces) {
158 for (var i in topLevelNamespaces)
159 this.require.tlns[i] = topLevelNamespaces[i];
160 };
161
162 window.initSender = function initSender() {
163
164 var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter;
165 var oop = window.require("ace/lib/oop");
166
167 var Sender = function() {};
168
169 (function() {
170
171 oop.implement(this, EventEmitter);
172
173 this.callback = function(data, callbackId) {
174 postMessage({
175 type: "call",
176 id: callbackId,
177 data: data
178 });
179 };
180
181 this.emit = function(name, data) {
182 postMessage({
183 type: "event",
184 name: name,
185 data: data
186 });
187 };
188
189 }).call(Sender.prototype);
190
191 return new Sender();
192 };
193
194 var main = window.main = null;
195 var sender = window.sender = null;
196
197 window.onmessage = function(e) {
198 var msg = e.data;
199 if (msg.event && sender) {
200 sender._signal(msg.event, msg.data);
201 }
202 else if (msg.command) {
203 if (main[msg.command])
204 main[msg.command].apply(main, msg.args);
205 else if (window[msg.command])
206 window[msg.command].apply(window, msg.args);
207 else
208 throw new Error("Unknown command:" + msg.command);
209 }
210 else if (msg.init) {
211 window.initBaseUrls(msg.tlns);
212 sender = window.sender = window.initSender();
213 var clazz = this.require(msg.module)[msg.classname];
214 main = window.main = new clazz(sender);
215 }
216 };
217 })(this);
218
219 ace.define("ace/lib/oop",[], function(require, exports, module){"use strict";
220 exports.inherits = function (ctor, superCtor) {
221 ctor.super_ = superCtor;
222 ctor.prototype = Object.create(superCtor.prototype, {
223 constructor: {
224 value: ctor,
225 enumerable: false,
226 writable: true,
227 configurable: true
228 }
229 });
230 };
231 exports.mixin = function (obj, mixin) {
232 for (var key in mixin) {
233 obj[key] = mixin[key];
234 }
235 return obj;
236 };
237 exports.implement = function (proto, mixin) {
238 exports.mixin(proto, mixin);
239 };
240
241 });
242
243 ace.define("ace/apply_delta",[], function(require, exports, module){"use strict";
244 function throwDeltaError(delta, errorText) {
245 console.log("Invalid Delta:", delta);
246 throw "Invalid Delta: " + errorText;
247 }
248 function positionInDocument(docLines, position) {
249 return position.row >= 0 && position.row < docLines.length &&
250 position.column >= 0 && position.column <= docLines[position.row].length;
251 }
252 function validateDelta(docLines, delta) {
253 if (delta.action != "insert" && delta.action != "remove")
254 throwDeltaError(delta, "delta.action must be 'insert' or 'remove'");
255 if (!(delta.lines instanceof Array))
256 throwDeltaError(delta, "delta.lines must be an Array");
257 if (!delta.start || !delta.end)
258 throwDeltaError(delta, "delta.start/end must be an present");
259 var start = delta.start;
260 if (!positionInDocument(docLines, delta.start))
261 throwDeltaError(delta, "delta.start must be contained in document");
262 var end = delta.end;
263 if (delta.action == "remove" && !positionInDocument(docLines, end))
264 throwDeltaError(delta, "delta.end must contained in document for 'remove' actions");
265 var numRangeRows = end.row - start.row;
266 var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0));
267 if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars)
268 throwDeltaError(delta, "delta.range must match delta lines");
269 }
270 exports.applyDelta = function (docLines, delta, doNotValidate) {
271 var row = delta.start.row;
272 var startColumn = delta.start.column;
273 var line = docLines[row] || "";
274 switch (delta.action) {
275 case "insert":
276 var lines = delta.lines;
277 if (lines.length === 1) {
278 docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn);
279 }
280 else {
281 var args = [row, 1].concat(delta.lines);
282 docLines.splice.apply(docLines, args);
283 docLines[row] = line.substring(0, startColumn) + docLines[row];
284 docLines[row + delta.lines.length - 1] += line.substring(startColumn);
285 }
286 break;
287 case "remove":
288 var endColumn = delta.end.column;
289 var endRow = delta.end.row;
290 if (row === endRow) {
291 docLines[row] = line.substring(0, startColumn) + line.substring(endColumn);
292 }
293 else {
294 docLines.splice(row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn));
295 }
296 break;
297 }
298 };
299
300 });
301
302 ace.define("ace/lib/event_emitter",[], function(require, exports, module){"use strict";
303 var EventEmitter = {};
304 var stopPropagation = function () { this.propagationStopped = true; };
305 var preventDefault = function () { this.defaultPrevented = true; };
306 EventEmitter._emit =
307 EventEmitter._dispatchEvent = function (eventName, e) {
308 this._eventRegistry || (this._eventRegistry = {});
309 this._defaultHandlers || (this._defaultHandlers = {});
310 var listeners = this._eventRegistry[eventName] || [];
311 var defaultHandler = this._defaultHandlers[eventName];
312 if (!listeners.length && !defaultHandler)
313 return;
314 if (typeof e != "object" || !e)
315 e = {};
316 if (!e.type)
317 e.type = eventName;
318 if (!e.stopPropagation)
319 e.stopPropagation = stopPropagation;
320 if (!e.preventDefault)
321 e.preventDefault = preventDefault;
322 listeners = listeners.slice();
323 for (var i = 0; i < listeners.length; i++) {
324 listeners[i](e, this);
325 if (e.propagationStopped)
326 break;
327 }
328 if (defaultHandler && !e.defaultPrevented)
329 return defaultHandler(e, this);
330 };
331 EventEmitter._signal = function (eventName, e) {
332 var listeners = (this._eventRegistry || {})[eventName];
333 if (!listeners)
334 return;
335 listeners = listeners.slice();
336 for (var i = 0; i < listeners.length; i++)
337 listeners[i](e, this);
338 };
339 EventEmitter.once = function (eventName, callback) {
340 var _self = this;
341 this.on(eventName, function newCallback() {
342 _self.off(eventName, newCallback);
343 callback.apply(null, arguments);
344 });
345 if (!callback) {
346 return new Promise(function (resolve) {
347 callback = resolve;
348 });
349 }
350 };
351 EventEmitter.setDefaultHandler = function (eventName, callback) {
352 var handlers = this._defaultHandlers;
353 if (!handlers)
354 handlers = this._defaultHandlers = { _disabled_: {} };
355 if (handlers[eventName]) {
356 var old = handlers[eventName];
357 var disabled = handlers._disabled_[eventName];
358 if (!disabled)
359 handlers._disabled_[eventName] = disabled = [];
360 disabled.push(old);
361 var i = disabled.indexOf(callback);
362 if (i != -1)
363 disabled.splice(i, 1);
364 }
365 handlers[eventName] = callback;
366 };
367 EventEmitter.removeDefaultHandler = function (eventName, callback) {
368 var handlers = this._defaultHandlers;
369 if (!handlers)
370 return;
371 var disabled = handlers._disabled_[eventName];
372 if (handlers[eventName] == callback) {
373 if (disabled)
374 this.setDefaultHandler(eventName, disabled.pop());
375 }
376 else if (disabled) {
377 var i = disabled.indexOf(callback);
378 if (i != -1)
379 disabled.splice(i, 1);
380 }
381 };
382 EventEmitter.on =
383 EventEmitter.addEventListener = function (eventName, callback, capturing) {
384 this._eventRegistry = this._eventRegistry || {};
385 var listeners = this._eventRegistry[eventName];
386 if (!listeners)
387 listeners = this._eventRegistry[eventName] = [];
388 if (listeners.indexOf(callback) == -1)
389 listeners[capturing ? "unshift" : "push"](callback);
390 return callback;
391 };
392 EventEmitter.off =
393 EventEmitter.removeListener =
394 EventEmitter.removeEventListener = function (eventName, callback) {
395 this._eventRegistry = this._eventRegistry || {};
396 var listeners = this._eventRegistry[eventName];
397 if (!listeners)
398 return;
399 var index = listeners.indexOf(callback);
400 if (index !== -1)
401 listeners.splice(index, 1);
402 };
403 EventEmitter.removeAllListeners = function (eventName) {
404 if (!eventName)
405 this._eventRegistry = this._defaultHandlers = undefined;
406 if (this._eventRegistry)
407 this._eventRegistry[eventName] = undefined;
408 if (this._defaultHandlers)
409 this._defaultHandlers[eventName] = undefined;
410 };
411 exports.EventEmitter = EventEmitter;
412
413 });
414
415 ace.define("ace/range",[], function(require, exports, module){"use strict";
416 var Range = /** @class */ (function () {
417 function Range(startRow, startColumn, endRow, endColumn) {
418 this.start = {
419 row: startRow,
420 column: startColumn
421 };
422 this.end = {
423 row: endRow,
424 column: endColumn
425 };
426 }
427 Range.prototype.isEqual = function (range) {
428 return this.start.row === range.start.row &&
429 this.end.row === range.end.row &&
430 this.start.column === range.start.column &&
431 this.end.column === range.end.column;
432 };
433 Range.prototype.toString = function () {
434 return ("Range: [" + this.start.row + "/" + this.start.column +
435 "] -> [" + this.end.row + "/" + this.end.column + "]");
436 };
437 Range.prototype.contains = function (row, column) {
438 return this.compare(row, column) == 0;
439 };
440 Range.prototype.compareRange = function (range) {
441 var cmp, end = range.end, start = range.start;
442 cmp = this.compare(end.row, end.column);
443 if (cmp == 1) {
444 cmp = this.compare(start.row, start.column);
445 if (cmp == 1) {
446 return 2;
447 }
448 else if (cmp == 0) {
449 return 1;
450 }
451 else {
452 return 0;
453 }
454 }
455 else if (cmp == -1) {
456 return -2;
457 }
458 else {
459 cmp = this.compare(start.row, start.column);
460 if (cmp == -1) {
461 return -1;
462 }
463 else if (cmp == 1) {
464 return 42;
465 }
466 else {
467 return 0;
468 }
469 }
470 };
471 Range.prototype.comparePoint = function (p) {
472 return this.compare(p.row, p.column);
473 };
474 Range.prototype.containsRange = function (range) {
475 return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
476 };
477 Range.prototype.intersects = function (range) {
478 var cmp = this.compareRange(range);
479 return (cmp == -1 || cmp == 0 || cmp == 1);
480 };
481 Range.prototype.isEnd = function (row, column) {
482 return this.end.row == row && this.end.column == column;
483 };
484 Range.prototype.isStart = function (row, column) {
485 return this.start.row == row && this.start.column == column;
486 };
487 Range.prototype.setStart = function (row, column) {
488 if (typeof row == "object") {
489 this.start.column = row.column;
490 this.start.row = row.row;
491 }
492 else {
493 this.start.row = row;
494 this.start.column = column;
495 }
496 };
497 Range.prototype.setEnd = function (row, column) {
498 if (typeof row == "object") {
499 this.end.column = row.column;
500 this.end.row = row.row;
501 }
502 else {
503 this.end.row = row;
504 this.end.column = column;
505 }
506 };
507 Range.prototype.inside = function (row, column) {
508 if (this.compare(row, column) == 0) {
509 if (this.isEnd(row, column) || this.isStart(row, column)) {
510 return false;
511 }
512 else {
513 return true;
514 }
515 }
516 return false;
517 };
518 Range.prototype.insideStart = function (row, column) {
519 if (this.compare(row, column) == 0) {
520 if (this.isEnd(row, column)) {
521 return false;
522 }
523 else {
524 return true;
525 }
526 }
527 return false;
528 };
529 Range.prototype.insideEnd = function (row, column) {
530 if (this.compare(row, column) == 0) {
531 if (this.isStart(row, column)) {
532 return false;
533 }
534 else {
535 return true;
536 }
537 }
538 return false;
539 };
540 Range.prototype.compare = function (row, column) {
541 if (!this.isMultiLine()) {
542 if (row === this.start.row) {
543 return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
544 }
545 }
546 if (row < this.start.row)
547 return -1;
548 if (row > this.end.row)
549 return 1;
550 if (this.start.row === row)
551 return column >= this.start.column ? 0 : -1;
552 if (this.end.row === row)
553 return column <= this.end.column ? 0 : 1;
554 return 0;
555 };
556 Range.prototype.compareStart = function (row, column) {
557 if (this.start.row == row && this.start.column == column) {
558 return -1;
559 }
560 else {
561 return this.compare(row, column);
562 }
563 };
564 Range.prototype.compareEnd = function (row, column) {
565 if (this.end.row == row && this.end.column == column) {
566 return 1;
567 }
568 else {
569 return this.compare(row, column);
570 }
571 };
572 Range.prototype.compareInside = function (row, column) {
573 if (this.end.row == row && this.end.column == column) {
574 return 1;
575 }
576 else if (this.start.row == row && this.start.column == column) {
577 return -1;
578 }
579 else {
580 return this.compare(row, column);
581 }
582 };
583 Range.prototype.clipRows = function (firstRow, lastRow) {
584 if (this.end.row > lastRow)
585 var end = { row: lastRow + 1, column: 0 };
586 else if (this.end.row < firstRow)
587 var end = { row: firstRow, column: 0 };
588 if (this.start.row > lastRow)
589 var start = { row: lastRow + 1, column: 0 };
590 else if (this.start.row < firstRow)
591 var start = { row: firstRow, column: 0 };
592 return Range.fromPoints(start || this.start, end || this.end);
593 };
594 Range.prototype.extend = function (row, column) {
595 var cmp = this.compare(row, column);
596 if (cmp == 0)
597 return this;
598 else if (cmp == -1)
599 var start = { row: row, column: column };
600 else
601 var end = { row: row, column: column };
602 return Range.fromPoints(start || this.start, end || this.end);
603 };
604 Range.prototype.isEmpty = function () {
605 return (this.start.row === this.end.row && this.start.column === this.end.column);
606 };
607 Range.prototype.isMultiLine = function () {
608 return (this.start.row !== this.end.row);
609 };
610 Range.prototype.clone = function () {
611 return Range.fromPoints(this.start, this.end);
612 };
613 Range.prototype.collapseRows = function () {
614 if (this.end.column == 0)
615 return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row - 1), 0);
616 else
617 return new Range(this.start.row, 0, this.end.row, 0);
618 };
619 Range.prototype.toScreenRange = function (session) {
620 var screenPosStart = session.documentToScreenPosition(this.start);
621 var screenPosEnd = session.documentToScreenPosition(this.end);
622 return new Range(screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column);
623 };
624 Range.prototype.moveBy = function (row, column) {
625 this.start.row += row;
626 this.start.column += column;
627 this.end.row += row;
628 this.end.column += column;
629 };
630 return Range;
631 }());
632 Range.fromPoints = function (start, end) {
633 return new Range(start.row, start.column, end.row, end.column);
634 };
635 Range.comparePoints = function (p1, p2) {
636 return p1.row - p2.row || p1.column - p2.column;
637 };
638 exports.Range = Range;
639
640 });
641
642 ace.define("ace/anchor",[], function(require, exports, module){"use strict";
643 var oop = require("./lib/oop");
644 var EventEmitter = require("./lib/event_emitter").EventEmitter;
645 var Anchor = /** @class */ (function () {
646 function Anchor(doc, row, column) {
647 this.$onChange = this.onChange.bind(this);
648 this.attach(doc);
649 if (typeof row != "number")
650 this.setPosition(row.row, row.column);
651 else
652 this.setPosition(row, column);
653 }
654 Anchor.prototype.getPosition = function () {
655 return this.$clipPositionToDocument(this.row, this.column);
656 };
657 Anchor.prototype.getDocument = function () {
658 return this.document;
659 };
660 Anchor.prototype.onChange = function (delta) {
661 if (delta.start.row == delta.end.row && delta.start.row != this.row)
662 return;
663 if (delta.start.row > this.row)
664 return;
665 var point = $getTransformedPoint(delta, { row: this.row, column: this.column }, this.$insertRight);
666 this.setPosition(point.row, point.column, true);
667 };
668 Anchor.prototype.setPosition = function (row, column, noClip) {
669 var pos;
670 if (noClip) {
671 pos = {
672 row: row,
673 column: column
674 };
675 }
676 else {
677 pos = this.$clipPositionToDocument(row, column);
678 }
679 if (this.row == pos.row && this.column == pos.column)
680 return;
681 var old = {
682 row: this.row,
683 column: this.column
684 };
685 this.row = pos.row;
686 this.column = pos.column;
687 this._signal("change", {
688 old: old,
689 value: pos
690 });
691 };
692 Anchor.prototype.detach = function () {
693 this.document.off("change", this.$onChange);
694 };
695 Anchor.prototype.attach = function (doc) {
696 this.document = doc || this.document;
697 this.document.on("change", this.$onChange);
698 };
699 Anchor.prototype.$clipPositionToDocument = function (row, column) {
700 var pos = {};
701 if (row >= this.document.getLength()) {
702 pos.row = Math.max(0, this.document.getLength() - 1);
703 pos.column = this.document.getLine(pos.row).length;
704 }
705 else if (row < 0) {
706 pos.row = 0;
707 pos.column = 0;
708 }
709 else {
710 pos.row = row;
711 pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
712 }
713 if (column < 0)
714 pos.column = 0;
715 return pos;
716 };
717 return Anchor;
718 }());
719 Anchor.prototype.$insertRight = false;
720 oop.implement(Anchor.prototype, EventEmitter);
721 function $pointsInOrder(point1, point2, equalPointsInOrder) {
722 var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column;
723 return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter);
724 }
725 function $getTransformedPoint(delta, point, moveIfEqual) {
726 var deltaIsInsert = delta.action == "insert";
727 var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row);
728 var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column);
729 var deltaStart = delta.start;
730 var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range.
731 if ($pointsInOrder(point, deltaStart, moveIfEqual)) {
732 return {
733 row: point.row,
734 column: point.column
735 };
736 }
737 if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) {
738 return {
739 row: point.row + deltaRowShift,
740 column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0)
741 };
742 }
743 return {
744 row: deltaStart.row,
745 column: deltaStart.column
746 };
747 }
748 exports.Anchor = Anchor;
749
750 });
751
752 ace.define("ace/document",[], function(require, exports, module){"use strict";
753 var oop = require("./lib/oop");
754 var applyDelta = require("./apply_delta").applyDelta;
755 var EventEmitter = require("./lib/event_emitter").EventEmitter;
756 var Range = require("./range").Range;
757 var Anchor = require("./anchor").Anchor;
758 var Document = /** @class */ (function () {
759 function Document(textOrLines) {
760 this.$lines = [""];
761 if (textOrLines.length === 0) {
762 this.$lines = [""];
763 }
764 else if (Array.isArray(textOrLines)) {
765 this.insertMergedLines({ row: 0, column: 0 }, textOrLines);
766 }
767 else {
768 this.insert({ row: 0, column: 0 }, textOrLines);
769 }
770 }
771 Document.prototype.setValue = function (text) {
772 var len = this.getLength() - 1;
773 this.remove(new Range(0, 0, len, this.getLine(len).length));
774 this.insert({ row: 0, column: 0 }, text || "");
775 };
776 Document.prototype.getValue = function () {
777 return this.getAllLines().join(this.getNewLineCharacter());
778 };
779 Document.prototype.createAnchor = function (row, column) {
780 return new Anchor(this, row, column);
781 };
782 Document.prototype.$detectNewLine = function (text) {
783 var match = text.match(/^.*?(\r\n|\r|\n)/m);
784 this.$autoNewLine = match ? match[1] : "\n";
785 this._signal("changeNewLineMode");
786 };
787 Document.prototype.getNewLineCharacter = function () {
788 switch (this.$newLineMode) {
789 case "windows":
790 return "\r\n";
791 case "unix":
792 return "\n";
793 default:
794 return this.$autoNewLine || "\n";
795 }
796 };
797 Document.prototype.setNewLineMode = function (newLineMode) {
798 if (this.$newLineMode === newLineMode)
799 return;
800 this.$newLineMode = newLineMode;
801 this._signal("changeNewLineMode");
802 };
803 Document.prototype.getNewLineMode = function () {
804 return this.$newLineMode;
805 };
806 Document.prototype.isNewLine = function (text) {
807 return (text == "\r\n" || text == "\r" || text == "\n");
808 };
809 Document.prototype.getLine = function (row) {
810 return this.$lines[row] || "";
811 };
812 Document.prototype.getLines = function (firstRow, lastRow) {
813 return this.$lines.slice(firstRow, lastRow + 1);
814 };
815 Document.prototype.getAllLines = function () {
816 return this.getLines(0, this.getLength());
817 };
818 Document.prototype.getLength = function () {
819 return this.$lines.length;
820 };
821 Document.prototype.getTextRange = function (range) {
822 return this.getLinesForRange(range).join(this.getNewLineCharacter());
823 };
824 Document.prototype.getLinesForRange = function (range) {
825 var lines;
826 if (range.start.row === range.end.row) {
827 lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)];
828 }
829 else {
830 lines = this.getLines(range.start.row, range.end.row);
831 lines[0] = (lines[0] || "").substring(range.start.column);
832 var l = lines.length - 1;
833 if (range.end.row - range.start.row == l)
834 lines[l] = lines[l].substring(0, range.end.column);
835 }
836 return lines;
837 };
838 Document.prototype.insertLines = function (row, lines) {
839 console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead.");
840 return this.insertFullLines(row, lines);
841 };
842 Document.prototype.removeLines = function (firstRow, lastRow) {
843 console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead.");
844 return this.removeFullLines(firstRow, lastRow);
845 };
846 Document.prototype.insertNewLine = function (position) {
847 console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.");
848 return this.insertMergedLines(position, ["", ""]);
849 };
850 Document.prototype.insert = function (position, text) {
851 if (this.getLength() <= 1)
852 this.$detectNewLine(text);
853 return this.insertMergedLines(position, this.$split(text));
854 };
855 Document.prototype.insertInLine = function (position, text) {
856 var start = this.clippedPos(position.row, position.column);
857 var end = this.pos(position.row, position.column + text.length);
858 this.applyDelta({
859 start: start,
860 end: end,
861 action: "insert",
862 lines: [text]
863 }, true);
864 return this.clonePos(end);
865 };
866 Document.prototype.clippedPos = function (row, column) {
867 var length = this.getLength();
868 if (row === undefined) {
869 row = length;
870 }
871 else if (row < 0) {
872 row = 0;
873 }
874 else if (row >= length) {
875 row = length - 1;
876 column = undefined;
877 }
878 var line = this.getLine(row);
879 if (column == undefined)
880 column = line.length;
881 column = Math.min(Math.max(column, 0), line.length);
882 return { row: row, column: column };
883 };
884 Document.prototype.clonePos = function (pos) {
885 return { row: pos.row, column: pos.column };
886 };
887 Document.prototype.pos = function (row, column) {
888 return { row: row, column: column };
889 };
890 Document.prototype.$clipPosition = function (position) {
891 var length = this.getLength();
892 if (position.row >= length) {
893 position.row = Math.max(0, length - 1);
894 position.column = this.getLine(length - 1).length;
895 }
896 else {
897 position.row = Math.max(0, position.row);
898 position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length);
899 }
900 return position;
901 };
902 Document.prototype.insertFullLines = function (row, lines) {
903 row = Math.min(Math.max(row, 0), this.getLength());
904 var column = 0;
905 if (row < this.getLength()) {
906 lines = lines.concat([""]);
907 column = 0;
908 }
909 else {
910 lines = [""].concat(lines);
911 row--;
912 column = this.$lines[row].length;
913 }
914 this.insertMergedLines({ row: row, column: column }, lines);
915 };
916 Document.prototype.insertMergedLines = function (position, lines) {
917 var start = this.clippedPos(position.row, position.column);
918 var end = {
919 row: start.row + lines.length - 1,
920 column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length
921 };
922 this.applyDelta({
923 start: start,
924 end: end,
925 action: "insert",
926 lines: lines
927 });
928 return this.clonePos(end);
929 };
930 Document.prototype.remove = function (range) {
931 var start = this.clippedPos(range.start.row, range.start.column);
932 var end = this.clippedPos(range.end.row, range.end.column);
933 this.applyDelta({
934 start: start,
935 end: end,
936 action: "remove",
937 lines: this.getLinesForRange({ start: start, end: end })
938 });
939 return this.clonePos(start);
940 };
941 Document.prototype.removeInLine = function (row, startColumn, endColumn) {
942 var start = this.clippedPos(row, startColumn);
943 var end = this.clippedPos(row, endColumn);
944 this.applyDelta({
945 start: start,
946 end: end,
947 action: "remove",
948 lines: this.getLinesForRange({ start: start, end: end })
949 }, true);
950 return this.clonePos(start);
951 };
952 Document.prototype.removeFullLines = function (firstRow, lastRow) {
953 firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1);
954 lastRow = Math.min(Math.max(0, lastRow), this.getLength() - 1);
955 var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0;
956 var deleteLastNewLine = lastRow < this.getLength() - 1;
957 var startRow = (deleteFirstNewLine ? firstRow - 1 : firstRow);
958 var startCol = (deleteFirstNewLine ? this.getLine(startRow).length : 0);
959 var endRow = (deleteLastNewLine ? lastRow + 1 : lastRow);
960 var endCol = (deleteLastNewLine ? 0 : this.getLine(endRow).length);
961 var range = new Range(startRow, startCol, endRow, endCol);
962 var deletedLines = this.$lines.slice(firstRow, lastRow + 1);
963 this.applyDelta({
964 start: range.start,
965 end: range.end,
966 action: "remove",
967 lines: this.getLinesForRange(range)
968 });
969 return deletedLines;
970 };
971 Document.prototype.removeNewLine = function (row) {
972 if (row < this.getLength() - 1 && row >= 0) {
973 this.applyDelta({
974 start: this.pos(row, this.getLine(row).length),
975 end: this.pos(row + 1, 0),
976 action: "remove",
977 lines: ["", ""]
978 });
979 }
980 };
981 Document.prototype.replace = function (range, text) {
982 if (!(range instanceof Range))
983 range = Range.fromPoints(range.start, range.end);
984 if (text.length === 0 && range.isEmpty())
985 return range.start;
986 if (text == this.getTextRange(range))
987 return range.end;
988 this.remove(range);
989 var end;
990 if (text) {
991 end = this.insert(range.start, text);
992 }
993 else {
994 end = range.start;
995 }
996 return end;
997 };
998 Document.prototype.applyDeltas = function (deltas) {
999 for (var i = 0; i < deltas.length; i++) {
1000 this.applyDelta(deltas[i]);
1001 }
1002 };
1003 Document.prototype.revertDeltas = function (deltas) {
1004 for (var i = deltas.length - 1; i >= 0; i--) {
1005 this.revertDelta(deltas[i]);
1006 }
1007 };
1008 Document.prototype.applyDelta = function (delta, doNotValidate) {
1009 var isInsert = delta.action == "insert";
1010 if (isInsert ? delta.lines.length <= 1 && !delta.lines[0]
1011 : !Range.comparePoints(delta.start, delta.end)) {
1012 return;
1013 }
1014 if (isInsert && delta.lines.length > 20000) {
1015 this.$splitAndapplyLargeDelta(delta, 20000);
1016 }
1017 else {
1018 applyDelta(this.$lines, delta, doNotValidate);
1019 this._signal("change", delta);
1020 }
1021 };
1022 Document.prototype.$safeApplyDelta = function (delta) {
1023 var docLength = this.$lines.length;
1024 if (delta.action == "remove" && delta.start.row < docLength && delta.end.row < docLength
1025 || delta.action == "insert" && delta.start.row <= docLength) {
1026 this.applyDelta(delta);
1027 }
1028 };
1029 Document.prototype.$splitAndapplyLargeDelta = function (delta, MAX) {
1030 var lines = delta.lines;
1031 var l = lines.length - MAX + 1;
1032 var row = delta.start.row;
1033 var column = delta.start.column;
1034 for (var from = 0, to = 0; from < l; from = to) {
1035 to += MAX - 1;
1036 var chunk = lines.slice(from, to);
1037 chunk.push("");
1038 this.applyDelta({
1039 start: this.pos(row + from, column),
1040 end: this.pos(row + to, column = 0),
1041 action: delta.action,
1042 lines: chunk
1043 }, true);
1044 }
1045 delta.lines = lines.slice(from);
1046 delta.start.row = row + from;
1047 delta.start.column = column;
1048 this.applyDelta(delta, true);
1049 };
1050 Document.prototype.revertDelta = function (delta) {
1051 this.$safeApplyDelta({
1052 start: this.clonePos(delta.start),
1053 end: this.clonePos(delta.end),
1054 action: (delta.action == "insert" ? "remove" : "insert"),
1055 lines: delta.lines.slice()
1056 });
1057 };
1058 Document.prototype.indexToPosition = function (index, startRow) {
1059 var lines = this.$lines || this.getAllLines();
1060 var newlineLength = this.getNewLineCharacter().length;
1061 for (var i = startRow || 0, l = lines.length; i < l; i++) {
1062 index -= lines[i].length + newlineLength;
1063 if (index < 0)
1064 return { row: i, column: index + lines[i].length + newlineLength };
1065 }
1066 return { row: l - 1, column: index + lines[l - 1].length + newlineLength };
1067 };
1068 Document.prototype.positionToIndex = function (pos, startRow) {
1069 var lines = this.$lines || this.getAllLines();
1070 var newlineLength = this.getNewLineCharacter().length;
1071 var index = 0;
1072 var row = Math.min(pos.row, lines.length);
1073 for (var i = startRow || 0; i < row; ++i)
1074 index += lines[i].length + newlineLength;
1075 return index + pos.column;
1076 };
1077 Document.prototype.$split = function (text) {
1078 return text.split(/\r\n|\r|\n/);
1079 };
1080 return Document;
1081 }());
1082 Document.prototype.$autoNewLine = "";
1083 Document.prototype.$newLineMode = "auto";
1084 oop.implement(Document.prototype, EventEmitter);
1085 exports.Document = Document;
1086
1087 });
1088
1089 ace.define("ace/lib/deep_copy",[], function(require, exports, module){exports.deepCopy = function deepCopy(obj) {
1090 if (typeof obj !== "object" || !obj)
1091 return obj;
1092 var copy;
1093 if (Array.isArray(obj)) {
1094 copy = [];
1095 for (var key = 0; key < obj.length; key++) {
1096 copy[key] = deepCopy(obj[key]);
1097 }
1098 return copy;
1099 }
1100 if (Object.prototype.toString.call(obj) !== "[object Object]")
1101 return obj;
1102 copy = {};
1103 for (var key in obj)
1104 copy[key] = deepCopy(obj[key]);
1105 return copy;
1106 };
1107
1108 });
1109
1110 ace.define("ace/lib/lang",[], function(require, exports, module){"use strict";
1111 exports.last = function (a) {
1112 return a[a.length - 1];
1113 };
1114 exports.stringReverse = function (string) {
1115 return string.split("").reverse().join("");
1116 };
1117 exports.stringRepeat = function (string, count) {
1118 var result = '';
1119 while (count > 0) {
1120 if (count & 1)
1121 result += string;
1122 if (count >>= 1)
1123 string += string;
1124 }
1125 return result;
1126 };
1127 var trimBeginRegexp = /^\s\s*/;
1128 var trimEndRegexp = /\s\s*$/;
1129 exports.stringTrimLeft = function (string) {
1130 return string.replace(trimBeginRegexp, '');
1131 };
1132 exports.stringTrimRight = function (string) {
1133 return string.replace(trimEndRegexp, '');
1134 };
1135 exports.copyObject = function (obj) {
1136 var copy = {};
1137 for (var key in obj) {
1138 copy[key] = obj[key];
1139 }
1140 return copy;
1141 };
1142 exports.copyArray = function (array) {
1143 var copy = [];
1144 for (var i = 0, l = array.length; i < l; i++) {
1145 if (array[i] && typeof array[i] == "object")
1146 copy[i] = this.copyObject(array[i]);
1147 else
1148 copy[i] = array[i];
1149 }
1150 return copy;
1151 };
1152 exports.deepCopy = require("./deep_copy").deepCopy;
1153 exports.arrayToMap = function (arr) {
1154 var map = {};
1155 for (var i = 0; i < arr.length; i++) {
1156 map[arr[i]] = 1;
1157 }
1158 return map;
1159 };
1160 exports.createMap = function (props) {
1161 var map = Object.create(null);
1162 for (var i in props) {
1163 map[i] = props[i];
1164 }
1165 return map;
1166 };
1167 exports.arrayRemove = function (array, value) {
1168 for (var i = 0; i <= array.length; i++) {
1169 if (value === array[i]) {
1170 array.splice(i, 1);
1171 }
1172 }
1173 };
1174 exports.escapeRegExp = function (str) {
1175 return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
1176 };
1177 exports.escapeHTML = function (str) {
1178 return ("" + str).replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;");
1179 };
1180 exports.getMatchOffsets = function (string, regExp) {
1181 var matches = [];
1182 string.replace(regExp, function (str) {
1183 matches.push({
1184 offset: arguments[arguments.length - 2],
1185 length: str.length
1186 });
1187 });
1188 return matches;
1189 };
1190 exports.deferredCall = function (fcn) {
1191 var timer = null;
1192 var callback = function () {
1193 timer = null;
1194 fcn();
1195 };
1196 var deferred = function (timeout) {
1197 deferred.cancel();
1198 timer = setTimeout(callback, timeout || 0);
1199 return deferred;
1200 };
1201 deferred.schedule = deferred;
1202 deferred.call = function () {
1203 this.cancel();
1204 fcn();
1205 return deferred;
1206 };
1207 deferred.cancel = function () {
1208 clearTimeout(timer);
1209 timer = null;
1210 return deferred;
1211 };
1212 deferred.isPending = function () {
1213 return timer;
1214 };
1215 return deferred;
1216 };
1217 exports.delayedCall = function (fcn, defaultTimeout) {
1218 var timer = null;
1219 var callback = function () {
1220 timer = null;
1221 fcn();
1222 };
1223 var _self = function (timeout) {
1224 if (timer == null)
1225 timer = setTimeout(callback, timeout || defaultTimeout);
1226 };
1227 _self.delay = function (timeout) {
1228 timer && clearTimeout(timer);
1229 timer = setTimeout(callback, timeout || defaultTimeout);
1230 };
1231 _self.schedule = _self;
1232 _self.call = function () {
1233 this.cancel();
1234 fcn();
1235 };
1236 _self.cancel = function () {
1237 timer && clearTimeout(timer);
1238 timer = null;
1239 };
1240 _self.isPending = function () {
1241 return timer;
1242 };
1243 return _self;
1244 };
1245 exports.supportsLookbehind = function () {
1246 try {
1247 new RegExp('(?<=.)');
1248 }
1249 catch (e) {
1250 return false;
1251 }
1252 return true;
1253 };
1254 exports.skipEmptyMatch = function (line, last, supportsUnicodeFlag) {
1255 return supportsUnicodeFlag && line.codePointAt(last) > 0xffff ? 2 : 1;
1256 };
1257
1258 });
1259
1260 ace.define("ace/worker/mirror",[], function(require, exports, module) {
1261 "use strict";
1262
1263 var Document = require("../document").Document;
1264 var lang = require("../lib/lang");
1265
1266 var Mirror = exports.Mirror = function(sender) {
1267 this.sender = sender;
1268 var doc = this.doc = new Document("");
1269
1270 var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this));
1271
1272 var _self = this;
1273 sender.on("change", function(e) {
1274 var data = e.data;
1275 if (data[0].start) {
1276 doc.applyDeltas(data);
1277 } else {
1278 for (var i = 0; i < data.length; i += 2) {
1279 var d, err;
1280 if (Array.isArray(data[i+1])) {
1281 d = {action: "insert", start: data[i], lines: data[i+1]};
1282 } else {
1283 d = {action: "remove", start: data[i], end: data[i+1]};
1284 }
1285
1286 if ((d.action == "insert" ? d.start : d.end).row >= doc.$lines.length) {
1287 err = new Error("Invalid delta");
1288 err.data = {
1289 path: _self.$path,
1290 linesLength: doc.$lines.length,
1291 start: d.start,
1292 end: d.end
1293 };
1294 throw err;
1295 }
1296
1297 doc.applyDelta(d, true);
1298 }
1299 }
1300 if (_self.$timeout)
1301 return deferredUpdate.schedule(_self.$timeout);
1302 _self.onUpdate();
1303 });
1304 };
1305
1306 (function() {
1307
1308 this.$timeout = 500;
1309
1310 this.setTimeout = function(timeout) {
1311 this.$timeout = timeout;
1312 };
1313
1314 this.setValue = function(value) {
1315 this.doc.setValue(value);
1316 this.deferredUpdate.schedule(this.$timeout);
1317 };
1318
1319 this.getValue = function(callbackId) {
1320 this.sender.callback(this.doc.getValue(), callbackId);
1321 };
1322
1323 this.onUpdate = function() {
1324 };
1325
1326 this.isPending = function() {
1327 return this.deferredUpdate.isPending();
1328 };
1329
1330 }).call(Mirror.prototype);
1331
1332 });
1333
1334 ace.define("ace/mode/lua/luaparse",[], function(require, exports, module) {
1335
1336 (function (root, name, factory) {
1337 factory(exports)
1338 }(this, 'luaparse', function (exports) {
1339 'use strict';
1340
1341 exports.version = "0.3.1";
1342
1343 var input, options, length, features, encodingMode;
1344 var defaultOptions = exports.defaultOptions = {
1345 wait: false
1346 , comments: true
1347 , scope: false
1348 , locations: false
1349 , ranges: false
1350 , onCreateNode: null
1351 , onCreateScope: null
1352 , onDestroyScope: null
1353 , onLocalDeclaration: null
1354 , luaVersion: '5.3'
1355 , encodingMode: 'none'
1356 };
1357
1358 function encodeUTF8(codepoint, highMask) {
1359 highMask = highMask || 0;
1360
1361 if (codepoint < 0x80) {
1362 return String.fromCharCode(codepoint);
1363 } else if (codepoint < 0x800) {
1364 return String.fromCharCode(
1365 highMask | 0xc0 | (codepoint >> 6) ,
1366 highMask | 0x80 | ( codepoint & 0x3f)
1367 );
1368 } else if (codepoint < 0x10000) {
1369 return String.fromCharCode(
1370 highMask | 0xe0 | (codepoint >> 12) ,
1371 highMask | 0x80 | ((codepoint >> 6) & 0x3f),
1372 highMask | 0x80 | ( codepoint & 0x3f)
1373 );
1374 } else /* istanbul ignore else */ if (codepoint < 0x110000) {
1375 return String.fromCharCode(
1376 highMask | 0xf0 | (codepoint >> 18) ,
1377 highMask | 0x80 | ((codepoint >> 12) & 0x3f),
1378 highMask | 0x80 | ((codepoint >> 6) & 0x3f),
1379 highMask | 0x80 | ( codepoint & 0x3f)
1380 );
1381 } else {
1382 return null;
1383 }
1384 }
1385
1386 function toHex(num, digits) {
1387 var result = num.toString(16);
1388 while (result.length < digits)
1389 result = '0' + result;
1390 return result;
1391 }
1392
1393 function checkChars(rx) {
1394 return function (s) {
1395 var m = rx.exec(s);
1396 if (!m)
1397 return s;
1398 raise(null, errors.invalidCodeUnit, toHex(m[0].charCodeAt(0), 4).toUpperCase());
1399 };
1400 }
1401
1402 var encodingModes = {
1403 'pseudo-latin1': {
1404 fixup: checkChars(/[^\x00-\xff]/),
1405 encodeByte: function (value) {
1406 if (value === null)
1407 return '';
1408 return String.fromCharCode(value);
1409 },
1410 encodeUTF8: function (codepoint) {
1411 return encodeUTF8(codepoint);
1412 },
1413 },
1414 'x-user-defined': {
1415 fixup: checkChars(/[^\x00-\x7f\uf780-\uf7ff]/),
1416 encodeByte: function (value) {
1417 if (value === null)
1418 return '';
1419 if (value >= 0x80)
1420 return String.fromCharCode(value | 0xf700);
1421 return String.fromCharCode(value);
1422 },
1423 encodeUTF8: function (codepoint) {
1424 return encodeUTF8(codepoint, 0xf700);
1425 }
1426 },
1427 'none': {
1428 discardStrings: true,
1429 fixup: function (s) {
1430 return s;
1431 },
1432 encodeByte: function (value) {
1433 return '';
1434 },
1435 encodeUTF8: function (codepoint) {
1436 return '';
1437 }
1438 }
1439 };
1440
1441 var EOF = 1, StringLiteral = 2, Keyword = 4, Identifier = 8
1442 , NumericLiteral = 16, Punctuator = 32, BooleanLiteral = 64
1443 , NilLiteral = 128, VarargLiteral = 256;
1444
1445 exports.tokenTypes = { EOF: EOF, StringLiteral: StringLiteral
1446 , Keyword: Keyword, Identifier: Identifier, NumericLiteral: NumericLiteral
1447 , Punctuator: Punctuator, BooleanLiteral: BooleanLiteral
1448 , NilLiteral: NilLiteral, VarargLiteral: VarargLiteral
1449 };
1450
1451 var errors = exports.errors = {
1452 unexpected: 'unexpected %1 \'%2\' near \'%3\''
1453 , unexpectedEOF: 'unexpected symbol near \'<eof>\''
1454 , expected: '\'%1\' expected near \'%2\''
1455 , expectedToken: '%1 expected near \'%2\''
1456 , unfinishedString: 'unfinished string near \'%1\''
1457 , malformedNumber: 'malformed number near \'%1\''
1458 , decimalEscapeTooLarge: 'decimal escape too large near \'%1\''
1459 , invalidEscape: 'invalid escape sequence near \'%1\''
1460 , hexadecimalDigitExpected: 'hexadecimal digit expected near \'%1\''
1461 , braceExpected: 'missing \'%1\' near \'%2\''
1462 , tooLargeCodepoint: 'UTF-8 value too large near \'%1\''
1463 , unfinishedLongString: 'unfinished long string (starting at line %1) near \'%2\''
1464 , unfinishedLongComment: 'unfinished long comment (starting at line %1) near \'%2\''
1465 , ambiguousSyntax: 'ambiguous syntax (function call x new statement) near \'%1\''
1466 , noLoopToBreak: 'no loop to break near \'%1\''
1467 , labelAlreadyDefined: 'label \'%1\' already defined on line %2'
1468 , labelNotVisible: 'no visible label \'%1\' for <goto>'
1469 , gotoJumpInLocalScope: '<goto %1> jumps into the scope of local \'%2\''
1470 , cannotUseVararg: 'cannot use \'...\' outside a vararg function near \'%1\''
1471 , invalidCodeUnit: 'code unit U+%1 is not allowed in the current encoding mode'
1472 };
1473
1474 var ast = exports.ast = {
1475 labelStatement: function(label) {
1476 return {
1477 type: 'LabelStatement'
1478 , label: label
1479 };
1480 }
1481
1482 , breakStatement: function() {
1483 return {
1484 type: 'BreakStatement'
1485 };
1486 }
1487
1488 , gotoStatement: function(label) {
1489 return {
1490 type: 'GotoStatement'
1491 , label: label
1492 };
1493 }
1494
1495 , returnStatement: function(args) {
1496 return {
1497 type: 'ReturnStatement'
1498 , 'arguments': args
1499 };
1500 }
1501
1502 , ifStatement: function(clauses) {
1503 return {
1504 type: 'IfStatement'
1505 , clauses: clauses
1506 };
1507 }
1508 , ifClause: function(condition, body) {
1509 return {
1510 type: 'IfClause'
1511 , condition: condition
1512 , body: body
1513 };
1514 }
1515 , elseifClause: function(condition, body) {
1516 return {
1517 type: 'ElseifClause'
1518 , condition: condition
1519 , body: body
1520 };
1521 }
1522 , elseClause: function(body) {
1523 return {
1524 type: 'ElseClause'
1525 , body: body
1526 };
1527 }
1528
1529 , whileStatement: function(condition, body) {
1530 return {
1531 type: 'WhileStatement'
1532 , condition: condition
1533 , body: body
1534 };
1535 }
1536
1537 , doStatement: function(body) {
1538 return {
1539 type: 'DoStatement'
1540 , body: body
1541 };
1542 }
1543
1544 , repeatStatement: function(condition, body) {
1545 return {
1546 type: 'RepeatStatement'
1547 , condition: condition
1548 , body: body
1549 };
1550 }
1551
1552 , localStatement: function(variables, init) {
1553 return {
1554 type: 'LocalStatement'
1555 , variables: variables
1556 , init: init
1557 };
1558 }
1559
1560 , assignmentStatement: function(variables, init) {
1561 return {
1562 type: 'AssignmentStatement'
1563 , variables: variables
1564 , init: init
1565 };
1566 }
1567
1568 , callStatement: function(expression) {
1569 return {
1570 type: 'CallStatement'
1571 , expression: expression
1572 };
1573 }
1574
1575 , functionStatement: function(identifier, parameters, isLocal, body) {
1576 return {
1577 type: 'FunctionDeclaration'
1578 , identifier: identifier
1579 , isLocal: isLocal
1580 , parameters: parameters
1581 , body: body
1582 };
1583 }
1584
1585 , forNumericStatement: function(variable, start, end, step, body) {
1586 return {
1587 type: 'ForNumericStatement'
1588 , variable: variable
1589 , start: start
1590 , end: end
1591 , step: step
1592 , body: body
1593 };
1594 }
1595
1596 , forGenericStatement: function(variables, iterators, body) {
1597 return {
1598 type: 'ForGenericStatement'
1599 , variables: variables
1600 , iterators: iterators
1601 , body: body
1602 };
1603 }
1604
1605 , chunk: function(body) {
1606 return {
1607 type: 'Chunk'
1608 , body: body
1609 };
1610 }
1611
1612 , identifier: function(name) {
1613 return {
1614 type: 'Identifier'
1615 , name: name
1616 };
1617 }
1618
1619 , literal: function(type, value, raw) {
1620 type = (type === StringLiteral) ? 'StringLiteral'
1621 : (type === NumericLiteral) ? 'NumericLiteral'
1622 : (type === BooleanLiteral) ? 'BooleanLiteral'
1623 : (type === NilLiteral) ? 'NilLiteral'
1624 : 'VarargLiteral';
1625
1626 return {
1627 type: type
1628 , value: value
1629 , raw: raw
1630 };
1631 }
1632
1633 , tableKey: function(key, value) {
1634 return {
1635 type: 'TableKey'
1636 , key: key
1637 , value: value
1638 };
1639 }
1640 , tableKeyString: function(key, value) {
1641 return {
1642 type: 'TableKeyString'
1643 , key: key
1644 , value: value
1645 };
1646 }
1647 , tableValue: function(value) {
1648 return {
1649 type: 'TableValue'
1650 , value: value
1651 };
1652 }
1653
1654
1655 , tableConstructorExpression: function(fields) {
1656 return {
1657 type: 'TableConstructorExpression'
1658 , fields: fields
1659 };
1660 }
1661 , binaryExpression: function(operator, left, right) {
1662 var type = ('and' === operator || 'or' === operator) ?
1663 'LogicalExpression' :
1664 'BinaryExpression';
1665
1666 return {
1667 type: type
1668 , operator: operator
1669 , left: left
1670 , right: right
1671 };
1672 }
1673 , unaryExpression: function(operator, argument) {
1674 return {
1675 type: 'UnaryExpression'
1676 , operator: operator
1677 , argument: argument
1678 };
1679 }
1680 , memberExpression: function(base, indexer, identifier) {
1681 return {
1682 type: 'MemberExpression'
1683 , indexer: indexer
1684 , identifier: identifier
1685 , base: base
1686 };
1687 }
1688
1689 , indexExpression: function(base, index) {
1690 return {
1691 type: 'IndexExpression'
1692 , base: base
1693 , index: index
1694 };
1695 }
1696
1697 , callExpression: function(base, args) {
1698 return {
1699 type: 'CallExpression'
1700 , base: base
1701 , 'arguments': args
1702 };
1703 }
1704
1705 , tableCallExpression: function(base, args) {
1706 return {
1707 type: 'TableCallExpression'
1708 , base: base
1709 , 'arguments': args
1710 };
1711 }
1712
1713 , stringCallExpression: function(base, argument) {
1714 return {
1715 type: 'StringCallExpression'
1716 , base: base
1717 , argument: argument
1718 };
1719 }
1720
1721 , comment: function(value, raw) {
1722 return {
1723 type: 'Comment'
1724 , value: value
1725 , raw: raw
1726 };
1727 }
1728 };
1729
1730 function finishNode(node) {
1731 if (trackLocations) {
1732 var location = locations.pop();
1733 location.complete();
1734 location.bless(node);
1735 }
1736 if (options.onCreateNode) options.onCreateNode(node);
1737 return node;
1738 }
1739
1740 var slice = Array.prototype.slice
1741 , toString = Object.prototype.toString
1742 ;
1743
1744 var indexOf = /* istanbul ignore next */ function (array, element) {
1745 for (var i = 0, length = array.length; i < length; ++i) {
1746 if (array[i] === element) return i;
1747 }
1748 return -1;
1749 };
1750 if (Array.prototype.indexOf)
1751 indexOf = function (array, element) {
1752 return array.indexOf(element);
1753 };
1754
1755 function indexOfObject(array, property, element) {
1756 for (var i = 0, length = array.length; i < length; ++i) {
1757 if (array[i][property] === element) return i;
1758 }
1759 return -1;
1760 }
1761
1762 function sprintf(format) {
1763 var args = slice.call(arguments, 1);
1764 format = format.replace(/%(\d)/g, function (match, index) {
1765 return '' + args[index - 1] || /* istanbul ignore next */ '';
1766 });
1767 return format;
1768 }
1769
1770 var assign = /* istanbul ignore next */ function (dest) {
1771 var args = slice.call(arguments, 1)
1772 , src, prop;
1773
1774 for (var i = 0, length = args.length; i < length; ++i) {
1775 src = args[i];
1776 for (prop in src)
1777 if (Object.prototype.hasOwnProperty.call(src, prop)) {
1778 dest[prop] = src[prop];
1779 }
1780 }
1781
1782 return dest;
1783 };
1784 if (Object.assign)
1785 assign = Object.assign;
1786
1787 exports.SyntaxError = SyntaxError;
1788
1789 function fixupError(e) {
1790 if (!Object.create)
1791 return e;
1792 return Object.create(e, {
1793 'line': { 'writable': true, value: e.line },
1794 'index': { 'writable': true, value: e.index },
1795 'column': { 'writable': true, value: e.column }
1796 });
1797 }
1798
1799 function raise(token) {
1800 var message = sprintf.apply(null, slice.call(arguments, 1))
1801 , error, col;
1802
1803 if (token === null || typeof token.line === 'undefined') {
1804 col = index - lineStart + 1;
1805 error = fixupError(new SyntaxError(sprintf('[%1:%2] %3', line, col, message)));
1806 error.index = index;
1807 error.line = line;
1808 error.column = col;
1809 } else {
1810 col = token.range[0] - token.lineStart;
1811 error = fixupError(new SyntaxError(sprintf('[%1:%2] %3', token.line, col, message)));
1812 error.line = token.line;
1813 error.index = token.range[0];
1814 error.column = col;
1815 }
1816 throw error;
1817 }
1818
1819 function tokenValue(token) {
1820 var raw = input.slice(token.range[0], token.range[1]);
1821 if (raw)
1822 return raw;
1823 return token.value;
1824 }
1825
1826 function raiseUnexpectedToken(type, token) {
1827 raise(token, errors.expectedToken, type, tokenValue(token));
1828 }
1829
1830 function unexpected(found) {
1831 var near = tokenValue(lookahead);
1832 if ('undefined' !== typeof found.type) {
1833 var type;
1834 switch (found.type) {
1835 case StringLiteral: type = 'string'; break;
1836 case Keyword: type = 'keyword'; break;
1837 case Identifier: type = 'identifier'; break;
1838 case NumericLiteral: type = 'number'; break;
1839 case Punctuator: type = 'symbol'; break;
1840 case BooleanLiteral: type = 'boolean'; break;
1841 case NilLiteral:
1842 return raise(found, errors.unexpected, 'symbol', 'nil', near);
1843 case EOF:
1844 return raise(found, errors.unexpectedEOF);
1845 }
1846 return raise(found, errors.unexpected, type, tokenValue(found), near);
1847 }
1848 return raise(found, errors.unexpected, 'symbol', found, near);
1849 }
1850
1851 var index
1852 , token
1853 , previousToken
1854 , lookahead
1855 , comments
1856 , tokenStart
1857 , line
1858 , lineStart;
1859
1860 exports.lex = lex;
1861
1862 function lex() {
1863 skipWhiteSpace();
1864 while (45 === input.charCodeAt(index) &&
1865 45 === input.charCodeAt(index + 1)) {
1866 scanComment();
1867 skipWhiteSpace();
1868 }
1869 if (index >= length) return {
1870 type : EOF
1871 , value: '<eof>'
1872 , line: line
1873 , lineStart: lineStart
1874 , range: [index, index]
1875 };
1876
1877 var charCode = input.charCodeAt(index)
1878 , next = input.charCodeAt(index + 1);
1879 tokenStart = index;
1880 if (isIdentifierStart(charCode)) return scanIdentifierOrKeyword();
1881
1882 switch (charCode) {
1883 case 39: case 34: // '"
1884 return scanStringLiteral();
1885
1886 case 48: case 49: case 50: case 51: case 52: case 53:
1887 case 54: case 55: case 56: case 57: // 0-9
1888 return scanNumericLiteral();
1889
1890 case 46: // .
1891 if (isDecDigit(next)) return scanNumericLiteral();
1892 if (46 === next) {
1893 if (46 === input.charCodeAt(index + 2)) return scanVarargLiteral();
1894 return scanPunctuator('..');
1895 }
1896 return scanPunctuator('.');
1897
1898 case 61: // =
1899 if (61 === next) return scanPunctuator('==');
1900 return scanPunctuator('=');
1901
1902 case 62: // >
1903 if (features.bitwiseOperators)
1904 if (62 === next) return scanPunctuator('>>');
1905 if (61 === next) return scanPunctuator('>=');
1906 return scanPunctuator('>');
1907
1908 case 60: // <
1909 if (features.bitwiseOperators)
1910 if (60 === next) return scanPunctuator('<<');
1911 if (61 === next) return scanPunctuator('<=');
1912 return scanPunctuator('<');
1913
1914 case 126: // ~
1915 if (61 === next) return scanPunctuator('~=');
1916 if (!features.bitwiseOperators)
1917 break;
1918 return scanPunctuator('~');
1919
1920 case 58: // :
1921 if (features.labels)
1922 if (58 === next) return scanPunctuator('::');
1923 return scanPunctuator(':');
1924
1925 case 91: // [
1926 if (91 === next || 61 === next) return scanLongStringLiteral();
1927 return scanPunctuator('[');
1928
1929 case 47: // /
1930 if (features.integerDivision)
1931 if (47 === next) return scanPunctuator('//');
1932 return scanPunctuator('/');
1933
1934 case 38: case 124: // & |
1935 if (!features.bitwiseOperators)
1936 break;
1937 case 42: case 94: case 37: case 44: case 123: case 125:
1938 case 93: case 40: case 41: case 59: case 35: case 45:
1939 case 43: // * ^ % , { } ] ( ) ; # - +
1940 return scanPunctuator(input.charAt(index));
1941 }
1942
1943 return unexpected(input.charAt(index));
1944 }
1945
1946 function consumeEOL() {
1947 var charCode = input.charCodeAt(index)
1948 , peekCharCode = input.charCodeAt(index + 1);
1949
1950 if (isLineTerminator(charCode)) {
1951 if (10 === charCode && 13 === peekCharCode) ++index;
1952 if (13 === charCode && 10 === peekCharCode) ++index;
1953 ++line;
1954 lineStart = ++index;
1955
1956 return true;
1957 }
1958 return false;
1959 }
1960
1961 function skipWhiteSpace() {
1962 while (index < length) {
1963 var charCode = input.charCodeAt(index);
1964 if (isWhiteSpace(charCode)) {
1965 ++index;
1966 } else if (!consumeEOL()) {
1967 break;
1968 }
1969 }
1970 }
1971
1972 function scanIdentifierOrKeyword() {
1973 var value, type;
1974 while (isIdentifierPart(input.charCodeAt(++index)));
1975 value = encodingMode.fixup(input.slice(tokenStart, index));
1976 if (isKeyword(value)) {
1977 type = Keyword;
1978 } else if ('true' === value || 'false' === value) {
1979 type = BooleanLiteral;
1980 value = ('true' === value);
1981 } else if ('nil' === value) {
1982 type = NilLiteral;
1983 value = null;
1984 } else {
1985 type = Identifier;
1986 }
1987
1988 return {
1989 type: type
1990 , value: value
1991 , line: line
1992 , lineStart: lineStart
1993 , range: [tokenStart, index]
1994 };
1995 }
1996
1997 function scanPunctuator(value) {
1998 index += value.length;
1999 return {
2000 type: Punctuator
2001 , value: value
2002 , line: line
2003 , lineStart: lineStart
2004 , range: [tokenStart, index]
2005 };
2006 }
2007
2008 function scanVarargLiteral() {
2009 index += 3;
2010 return {
2011 type: VarargLiteral
2012 , value: '...'
2013 , line: line
2014 , lineStart: lineStart
2015 , range: [tokenStart, index]
2016 };
2017 }
2018
2019 function scanStringLiteral() {
2020 var delimiter = input.charCodeAt(index++)
2021 , beginLine = line
2022 , beginLineStart = lineStart
2023 , stringStart = index
2024 , string = encodingMode.discardStrings ? null : ''
2025 , charCode;
2026
2027 for (;;) {
2028 charCode = input.charCodeAt(index++);
2029 if (delimiter === charCode) break;
2030 if (index > length || isLineTerminator(charCode)) {
2031 string += input.slice(stringStart, index - 1);
2032 raise(null, errors.unfinishedString, input.slice(tokenStart, index - 1));
2033 }
2034 if (92 === charCode) { // backslash
2035 if (!encodingMode.discardStrings) {
2036 var beforeEscape = input.slice(stringStart, index - 1);
2037 string += encodingMode.fixup(beforeEscape);
2038 }
2039 var escapeValue = readEscapeSequence();
2040 if (!encodingMode.discardStrings)
2041 string += escapeValue;
2042 stringStart = index;
2043 }
2044 }
2045 if (!encodingMode.discardStrings) {
2046 string += encodingMode.encodeByte(null);
2047 string += encodingMode.fixup(input.slice(stringStart, index - 1));
2048 }
2049
2050 return {
2051 type: StringLiteral
2052 , value: string
2053 , line: beginLine
2054 , lineStart: beginLineStart
2055 , lastLine: line
2056 , lastLineStart: lineStart
2057 , range: [tokenStart, index]
2058 };
2059 }
2060
2061 function scanLongStringLiteral() {
2062 var beginLine = line
2063 , beginLineStart = lineStart
2064 , string = readLongString(false);
2065 if (false === string) raise(token, errors.expected, '[', tokenValue(token));
2066
2067 return {
2068 type: StringLiteral
2069 , value: encodingMode.discardStrings ? null : encodingMode.fixup(string)
2070 , line: beginLine
2071 , lineStart: beginLineStart
2072 , lastLine: line
2073 , lastLineStart: lineStart
2074 , range: [tokenStart, index]
2075 };
2076 }
2077
2078 function scanNumericLiteral() {
2079 var character = input.charAt(index)
2080 , next = input.charAt(index + 1);
2081
2082 var literal = ('0' === character && 'xX'.indexOf(next || null) >= 0) ?
2083 readHexLiteral() : readDecLiteral();
2084
2085 var foundImaginaryUnit = readImaginaryUnitSuffix()
2086 , foundInt64Suffix = readInt64Suffix();
2087
2088 if (foundInt64Suffix && (foundImaginaryUnit || literal.hasFractionPart)) {
2089 raise(null, errors.malformedNumber, input.slice(tokenStart, index));
2090 }
2091
2092 return {
2093 type: NumericLiteral
2094 , value: literal.value
2095 , line: line
2096 , lineStart: lineStart
2097 , range: [tokenStart, index]
2098 };
2099 }
2100
2101 function readImaginaryUnitSuffix() {
2102 if (!features.imaginaryNumbers) return;
2103 if ('iI'.indexOf(input.charAt(index) || null) >= 0) {
2104 ++index;
2105 return true;
2106 } else {
2107 return false;
2108 }
2109 }
2110
2111 function readInt64Suffix() {
2112 if (!features.integerSuffixes) return;
2113
2114 if ('uU'.indexOf(input.charAt(index) || null) >= 0) {
2115 ++index;
2116 if ('lL'.indexOf(input.charAt(index) || null) >= 0) {
2117 ++index;
2118 if ('lL'.indexOf(input.charAt(index) || null) >= 0) {
2119 ++index;
2120 return 'ULL';
2121 } else {
2122 raise(null, errors.malformedNumber, input.slice(tokenStart, index));
2123 }
2124 } else {
2125 raise(null, errors.malformedNumber, input.slice(tokenStart, index));
2126 }
2127 } else if ('lL'.indexOf(input.charAt(index) || null) >= 0) {
2128 ++index;
2129 if ('lL'.indexOf(input.charAt(index) || null) >= 0) {
2130 ++index;
2131 return 'LL';
2132 } else {
2133 raise(null, errors.malformedNumber, input.slice(tokenStart, index));
2134 }
2135 }
2136 }
2137
2138 function readHexLiteral() {
2139 var fraction = 0 // defaults to 0 as it gets summed
2140 , binaryExponent = 1 // defaults to 1 as it gets multiplied
2141 , binarySign = 1 // positive
2142 , digit, fractionStart, exponentStart, digitStart;
2143
2144 digitStart = index += 2; // Skip 0x part
2145 if (!isHexDigit(input.charCodeAt(index)))
2146 raise(null, errors.malformedNumber, input.slice(tokenStart, index));
2147
2148 while (isHexDigit(input.charCodeAt(index))) ++index;
2149 digit = parseInt(input.slice(digitStart, index), 16);
2150 var foundFraction = false;
2151 if ('.' === input.charAt(index)) {
2152 foundFraction = true;
2153 fractionStart = ++index;
2154
2155 while (isHexDigit(input.charCodeAt(index))) ++index;
2156 fraction = input.slice(fractionStart, index);
2157 fraction = (fractionStart === index) ? 0
2158 : parseInt(fraction, 16) / Math.pow(16, index - fractionStart);
2159 }
2160 var foundBinaryExponent = false;
2161 if ('pP'.indexOf(input.charAt(index) || null) >= 0) {
2162 foundBinaryExponent = true;
2163 ++index;
2164 if ('+-'.indexOf(input.charAt(index) || null) >= 0)
2165 binarySign = ('+' === input.charAt(index++)) ? 1 : -1;
2166
2167 exponentStart = index;
2168 if (!isDecDigit(input.charCodeAt(index)))
2169 raise(null, errors.malformedNumber, input.slice(tokenStart, index));
2170
2171 while (isDecDigit(input.charCodeAt(index))) ++index;
2172 binaryExponent = input.slice(exponentStart, index);
2173 binaryExponent = Math.pow(2, binaryExponent * binarySign);
2174 }
2175
2176 return {
2177 value: (digit + fraction) * binaryExponent,
2178 hasFractionPart: foundFraction || foundBinaryExponent
2179 };
2180 }
2181
2182 function readDecLiteral() {
2183 while (isDecDigit(input.charCodeAt(index))) ++index;
2184 var foundFraction = false;
2185 if ('.' === input.charAt(index)) {
2186 foundFraction = true;
2187 ++index;
2188 while (isDecDigit(input.charCodeAt(index))) ++index;
2189 }
2190 var foundExponent = false;
2191 if ('eE'.indexOf(input.charAt(index) || null) >= 0) {
2192 foundExponent = true;
2193 ++index;
2194 if ('+-'.indexOf(input.charAt(index) || null) >= 0) ++index;
2195 if (!isDecDigit(input.charCodeAt(index)))
2196 raise(null, errors.malformedNumber, input.slice(tokenStart, index));
2197
2198 while (isDecDigit(input.charCodeAt(index))) ++index;
2199 }
2200
2201 return {
2202 value: parseFloat(input.slice(tokenStart, index)),
2203 hasFractionPart: foundFraction || foundExponent
2204 };
2205 }
2206
2207 function readUnicodeEscapeSequence() {
2208 var sequenceStart = index++;
2209
2210 if (input.charAt(index++) !== '{')
2211 raise(null, errors.braceExpected, '{', '\\' + input.slice(sequenceStart, index));
2212 if (!isHexDigit(input.charCodeAt(index)))
2213 raise(null, errors.hexadecimalDigitExpected, '\\' + input.slice(sequenceStart, index));
2214
2215 while (input.charCodeAt(index) === 0x30) ++index;
2216 var escStart = index;
2217
2218 while (isHexDigit(input.charCodeAt(index))) {
2219 ++index;
2220 if (index - escStart > 6)
2221 raise(null, errors.tooLargeCodepoint, '\\' + input.slice(sequenceStart, index));
2222 }
2223
2224 var b = input.charAt(index++);
2225 if (b !== '}') {
2226 if ((b === '"') || (b === "'"))
2227 raise(null, errors.braceExpected, '}', '\\' + input.slice(sequenceStart, index--));
2228 else
2229 raise(null, errors.hexadecimalDigitExpected, '\\' + input.slice(sequenceStart, index));
2230 }
2231
2232 var codepoint = parseInt(input.slice(escStart, index - 1) || '0', 16);
2233 var frag = '\\' + input.slice(sequenceStart, index);
2234
2235 if (codepoint > 0x10ffff) {
2236 raise(null, errors.tooLargeCodepoint, frag);
2237 }
2238
2239 return encodingMode.encodeUTF8(codepoint, frag);
2240 }
2241 function readEscapeSequence() {
2242 var sequenceStart = index;
2243 switch (input.charAt(index)) {
2244 case 'a': ++index; return '\x07';
2245 case 'n': ++index; return '\n';
2246 case 'r': ++index; return '\r';
2247 case 't': ++index; return '\t';
2248 case 'v': ++index; return '\x0b';
2249 case 'b': ++index; return '\b';
2250 case 'f': ++index; return '\f';
2251 case '\r':
2252 case '\n':
2253 consumeEOL();
2254 return '\n';
2255
2256 case '0': case '1': case '2': case '3': case '4':
2257 case '5': case '6': case '7': case '8': case '9':
2258 while (isDecDigit(input.charCodeAt(index)) && index - sequenceStart < 3) ++index;
2259
2260 var frag = input.slice(sequenceStart, index);
2261 var ddd = parseInt(frag, 10);
2262 if (ddd > 255) {
2263 raise(null, errors.decimalEscapeTooLarge, '\\' + ddd);
2264 }
2265 return encodingMode.encodeByte(ddd, '\\' + frag);
2266
2267 case 'z':
2268 if (features.skipWhitespaceEscape) {
2269 ++index;
2270 skipWhiteSpace();
2271 return '';
2272 }
2273 break;
2274
2275 case 'x':
2276 if (features.hexEscapes) {
2277 if (isHexDigit(input.charCodeAt(index + 1)) &&
2278 isHexDigit(input.charCodeAt(index + 2))) {
2279 index += 3;
2280 return encodingMode.encodeByte(parseInt(input.slice(sequenceStart + 1, index), 16), '\\' + input.slice(sequenceStart, index));
2281 }
2282 raise(null, errors.hexadecimalDigitExpected, '\\' + input.slice(sequenceStart, index + 2));
2283 }
2284 break;
2285
2286 case 'u':
2287 if (features.unicodeEscapes)
2288 return readUnicodeEscapeSequence();
2289 break;
2290
2291 case '\\': case '"': case "'":
2292 return input.charAt(index++);
2293 }
2294
2295 if (features.strictEscapes)
2296 raise(null, errors.invalidEscape, '\\' + input.slice(sequenceStart, index + 1));
2297 return input.charAt(index++);
2298 }
2299
2300 function scanComment() {
2301 tokenStart = index;
2302 index += 2; // --
2303
2304 var character = input.charAt(index)
2305 , content = ''
2306 , isLong = false
2307 , commentStart = index
2308 , lineStartComment = lineStart
2309 , lineComment = line;
2310
2311 if ('[' === character) {
2312 content = readLongString(true);
2313 if (false === content) content = character;
2314 else isLong = true;
2315 }
2316 if (!isLong) {
2317 while (index < length) {
2318 if (isLineTerminator(input.charCodeAt(index))) break;
2319 ++index;
2320 }
2321 if (options.comments) content = input.slice(commentStart, index);
2322 }
2323
2324 if (options.comments) {
2325 var node = ast.comment(content, input.slice(tokenStart, index));
2326 if (options.locations) {
2327 node.loc = {
2328 start: { line: lineComment, column: tokenStart - lineStartComment }
2329 , end: { line: line, column: index - lineStart }
2330 };
2331 }
2332 if (options.ranges) {
2333 node.range = [tokenStart, index];
2334 }
2335 if (options.onCreateNode) options.onCreateNode(node);
2336 comments.push(node);
2337 }
2338 }
2339
2340 function readLongString(isComment) {
2341 var level = 0
2342 , content = ''
2343 , terminator = false
2344 , character, stringStart, firstLine = line;
2345
2346 ++index; // [
2347 while ('=' === input.charAt(index + level)) ++level;
2348 if ('[' !== input.charAt(index + level)) return false;
2349
2350 index += level + 1;
2351 if (isLineTerminator(input.charCodeAt(index))) consumeEOL();
2352
2353 stringStart = index;
2354 while (index < length) {
2355 while (isLineTerminator(input.charCodeAt(index))) consumeEOL();
2356
2357 character = input.charAt(index++);
2358 if (']' === character) {
2359 terminator = true;
2360 for (var i = 0; i < level; ++i) {
2361 if ('=' !== input.charAt(index + i)) terminator = false;
2362 }
2363 if (']' !== input.charAt(index + level)) terminator = false;
2364 }
2365 if (terminator) {
2366 content += input.slice(stringStart, index - 1);
2367 index += level + 1;
2368 return content;
2369 }
2370 }
2371
2372 raise(null, isComment ?
2373 errors.unfinishedLongComment :
2374 errors.unfinishedLongString,
2375 firstLine, '<eof>');
2376 }
2377
2378 function next() {
2379 previousToken = token;
2380 token = lookahead;
2381 lookahead = lex();
2382 }
2383
2384 function consume(value) {
2385 if (value === token.value) {
2386 next();
2387 return true;
2388 }
2389 return false;
2390 }
2391
2392 function expect(value) {
2393 if (value === token.value) next();
2394 else raise(token, errors.expected, value, tokenValue(token));
2395 }
2396
2397 function isWhiteSpace(charCode) {
2398 return 9 === charCode || 32 === charCode || 0xB === charCode || 0xC === charCode;
2399 }
2400
2401 function isLineTerminator(charCode) {
2402 return 10 === charCode || 13 === charCode;
2403 }
2404
2405 function isDecDigit(charCode) {
2406 return charCode >= 48 && charCode <= 57;
2407 }
2408
2409 function isHexDigit(charCode) {
2410 return (charCode >= 48 && charCode <= 57) || (charCode >= 97 && charCode <= 102) || (charCode >= 65 && charCode <= 70);
2411 }
2412
2413 function isIdentifierStart(charCode) {
2414 if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || 95 === charCode)
2415 return true;
2416 if (features.extendedIdentifiers && charCode >= 128)
2417 return true;
2418 return false;
2419 }
2420
2421 function isIdentifierPart(charCode) {
2422 if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || 95 === charCode || (charCode >= 48 && charCode <= 57))
2423 return true;
2424 if (features.extendedIdentifiers && charCode >= 128)
2425 return true;
2426 return false;
2427 }
2428
2429 function isKeyword(id) {
2430 switch (id.length) {
2431 case 2:
2432 return 'do' === id || 'if' === id || 'in' === id || 'or' === id;
2433 case 3:
2434 return 'and' === id || 'end' === id || 'for' === id || 'not' === id;
2435 case 4:
2436 if ('else' === id || 'then' === id)
2437 return true;
2438 if (features.labels && !features.contextualGoto)
2439 return ('goto' === id);
2440 return false;
2441 case 5:
2442 return 'break' === id || 'local' === id || 'until' === id || 'while' === id;
2443 case 6:
2444 return 'elseif' === id || 'repeat' === id || 'return' === id;
2445 case 8:
2446 return 'function' === id;
2447 }
2448 return false;
2449 }
2450
2451 function isUnary(token) {
2452 if (Punctuator === token.type) return '#-~'.indexOf(token.value) >= 0;
2453 if (Keyword === token.type) return 'not' === token.value;
2454 return false;
2455 }
2456
2457 function isBlockFollow(token) {
2458 if (EOF === token.type) return true;
2459 if (Keyword !== token.type) return false;
2460 switch (token.value) {
2461 case 'else': case 'elseif':
2462 case 'end': case 'until':
2463 return true;
2464 default:
2465 return false;
2466 }
2467 }
2468 var scopes
2469 , scopeDepth
2470 , globals;
2471 function createScope() {
2472 var scope = scopes[scopeDepth++].slice();
2473 scopes.push(scope);
2474 if (options.onCreateScope) options.onCreateScope();
2475 }
2476 function destroyScope() {
2477 var scope = scopes.pop();
2478 --scopeDepth;
2479 if (options.onDestroyScope) options.onDestroyScope();
2480 }
2481 function scopeIdentifierName(name) {
2482 if (options.onLocalDeclaration) options.onLocalDeclaration(name);
2483 if (-1 !== indexOf(scopes[scopeDepth], name)) return;
2484 scopes[scopeDepth].push(name);
2485 }
2486 function scopeIdentifier(node) {
2487 scopeIdentifierName(node.name);
2488 attachScope(node, true);
2489 }
2490 function attachScope(node, isLocal) {
2491 if (!isLocal && -1 === indexOfObject(globals, 'name', node.name))
2492 globals.push(node);
2493
2494 node.isLocal = isLocal;
2495 }
2496 function scopeHasName(name) {
2497 return (-1 !== indexOf(scopes[scopeDepth], name));
2498 }
2499
2500 var locations = []
2501 , trackLocations;
2502
2503 function createLocationMarker() {
2504 return new Marker(token);
2505 }
2506
2507 function Marker(token) {
2508 if (options.locations) {
2509 this.loc = {
2510 start: {
2511 line: token.line
2512 , column: token.range[0] - token.lineStart
2513 }
2514 , end: {
2515 line: 0
2516 , column: 0
2517 }
2518 };
2519 }
2520 if (options.ranges) this.range = [token.range[0], 0];
2521 }
2522 Marker.prototype.complete = function() {
2523 if (options.locations) {
2524 this.loc.end.line = previousToken.lastLine || previousToken.line;
2525 this.loc.end.column = previousToken.range[1] - (previousToken.lastLineStart || previousToken.lineStart);
2526 }
2527 if (options.ranges) {
2528 this.range[1] = previousToken.range[1];
2529 }
2530 };
2531
2532 Marker.prototype.bless = function (node) {
2533 if (this.loc) {
2534 var loc = this.loc;
2535 node.loc = {
2536 start: {
2537 line: loc.start.line,
2538 column: loc.start.column
2539 },
2540 end: {
2541 line: loc.end.line,
2542 column: loc.end.column
2543 }
2544 };
2545 }
2546 if (this.range) {
2547 node.range = [
2548 this.range[0],
2549 this.range[1]
2550 ];
2551 }
2552 };
2553 function markLocation() {
2554 if (trackLocations) locations.push(createLocationMarker());
2555 }
2556 function pushLocation(marker) {
2557 if (trackLocations) locations.push(marker);
2558 }
2559
2560 function FullFlowContext() {
2561 this.scopes = [];
2562 this.pendingGotos = [];
2563 }
2564
2565 FullFlowContext.prototype.isInLoop = function () {
2566 var i = this.scopes.length;
2567 while (i --> 0) {
2568 if (this.scopes[i].isLoop)
2569 return true;
2570 }
2571 return false;
2572 };
2573
2574 FullFlowContext.prototype.pushScope = function (isLoop) {
2575 var scope = {
2576 labels: {},
2577 locals: [],
2578 deferredGotos: [],
2579 isLoop: !!isLoop
2580 };
2581 this.scopes.push(scope);
2582 };
2583
2584 FullFlowContext.prototype.popScope = function () {
2585 for (var i = 0; i < this.pendingGotos.length; ++i) {
2586 var theGoto = this.pendingGotos[i];
2587 if (theGoto.maxDepth >= this.scopes.length)
2588 if (--theGoto.maxDepth <= 0)
2589 raise(theGoto.token, errors.labelNotVisible, theGoto.target);
2590 }
2591
2592 this.scopes.pop();
2593 };
2594
2595 FullFlowContext.prototype.addGoto = function (target, token) {
2596 var localCounts = [];
2597
2598 for (var i = 0; i < this.scopes.length; ++i) {
2599 var scope = this.scopes[i];
2600 localCounts.push(scope.locals.length);
2601 if (Object.prototype.hasOwnProperty.call(scope.labels, target))
2602 return;
2603 }
2604
2605 this.pendingGotos.push({
2606 maxDepth: this.scopes.length,
2607 target: target,
2608 token: token,
2609 localCounts: localCounts
2610 });
2611 };
2612
2613 FullFlowContext.prototype.addLabel = function (name, token) {
2614 var scope = this.currentScope();
2615
2616 if (Object.prototype.hasOwnProperty.call(scope.labels, name)) {
2617 raise(token, errors.labelAlreadyDefined, name, scope.labels[name].line);
2618 } else {
2619 var newGotos = [];
2620
2621 for (var i = 0; i < this.pendingGotos.length; ++i) {
2622 var theGoto = this.pendingGotos[i];
2623
2624 if (theGoto.maxDepth >= this.scopes.length && theGoto.target === name) {
2625 if (theGoto.localCounts[this.scopes.length - 1] < scope.locals.length) {
2626 scope.deferredGotos.push(theGoto);
2627 }
2628 continue;
2629 }
2630
2631 newGotos.push(theGoto);
2632 }
2633
2634 this.pendingGotos = newGotos;
2635 }
2636
2637 scope.labels[name] = {
2638 localCount: scope.locals.length,
2639 line: token.line
2640 };
2641 };
2642
2643 FullFlowContext.prototype.addLocal = function (name, token) {
2644 this.currentScope().locals.push({
2645 name: name,
2646 token: token
2647 });
2648 };
2649
2650 FullFlowContext.prototype.currentScope = function () {
2651 return this.scopes[this.scopes.length - 1];
2652 };
2653
2654 FullFlowContext.prototype.raiseDeferredErrors = function () {
2655 var scope = this.currentScope();
2656 var bads = scope.deferredGotos;
2657 for (var i = 0; i < bads.length; ++i) {
2658 var theGoto = bads[i];
2659 raise(theGoto.token, errors.gotoJumpInLocalScope, theGoto.target, scope.locals[theGoto.localCounts[this.scopes.length - 1]].name);
2660 }
2661 };
2662
2663 function LoopFlowContext() {
2664 this.level = 0;
2665 this.loopLevels = [];
2666 }
2667
2668 LoopFlowContext.prototype.isInLoop = function () {
2669 return !!this.loopLevels.length;
2670 };
2671
2672 LoopFlowContext.prototype.pushScope = function (isLoop) {
2673 ++this.level;
2674 if (isLoop)
2675 this.loopLevels.push(this.level);
2676 };
2677
2678 LoopFlowContext.prototype.popScope = function () {
2679 var levels = this.loopLevels;
2680 var levlen = levels.length;
2681 if (levlen) {
2682 if (levels[levlen - 1] === this.level)
2683 levels.pop();
2684 }
2685 --this.level;
2686 };
2687
2688 LoopFlowContext.prototype.addGoto =
2689 LoopFlowContext.prototype.addLabel =
2690 function () { throw new Error('This should never happen'); };
2691
2692 LoopFlowContext.prototype.addLocal =
2693 LoopFlowContext.prototype.raiseDeferredErrors =
2694 function () {};
2695
2696 function makeFlowContext() {
2697 return features.labels ? new FullFlowContext() : new LoopFlowContext();
2698 }
2699
2700 function parseChunk() {
2701 next();
2702 markLocation();
2703 if (options.scope) createScope();
2704 var flowContext = makeFlowContext();
2705 flowContext.allowVararg = true;
2706 flowContext.pushScope();
2707 var body = parseBlock(flowContext);
2708 flowContext.popScope();
2709 if (options.scope) destroyScope();
2710 if (EOF !== token.type) unexpected(token);
2711 if (trackLocations && !body.length) previousToken = token;
2712 return finishNode(ast.chunk(body));
2713 }
2714
2715 function parseBlock(flowContext) {
2716 var block = []
2717 , statement;
2718
2719 while (!isBlockFollow(token)) {
2720 if ('return' === token.value || (!features.relaxedBreak && 'break' === token.value)) {
2721 block.push(parseStatement(flowContext));
2722 break;
2723 }
2724 statement = parseStatement(flowContext);
2725 consume(';');
2726 if (statement) block.push(statement);
2727 }
2728 return block;
2729 }
2730
2731 function parseStatement(flowContext) {
2732 markLocation();
2733
2734 if (Punctuator === token.type) {
2735 if (consume('::')) return parseLabelStatement(flowContext);
2736 }
2737 if (features.emptyStatement) {
2738 if (consume(';')) {
2739 if (trackLocations) locations.pop();
2740 return;
2741 }
2742 }
2743
2744 flowContext.raiseDeferredErrors();
2745
2746 if (Keyword === token.type) {
2747 switch (token.value) {
2748 case 'local': next(); return parseLocalStatement(flowContext);
2749 case 'if': next(); return parseIfStatement(flowContext);
2750 case 'return': next(); return parseReturnStatement(flowContext);
2751 case 'function': next();
2752 var name = parseFunctionName();
2753 return parseFunctionDeclaration(name);
2754 case 'while': next(); return parseWhileStatement(flowContext);
2755 case 'for': next(); return parseForStatement(flowContext);
2756 case 'repeat': next(); return parseRepeatStatement(flowContext);
2757 case 'break': next();
2758 if (!flowContext.isInLoop())
2759 raise(token, errors.noLoopToBreak, token.value);
2760 return parseBreakStatement();
2761 case 'do': next(); return parseDoStatement(flowContext);
2762 case 'goto': next(); return parseGotoStatement(flowContext);
2763 }
2764 }
2765
2766 if (features.contextualGoto &&
2767 token.type === Identifier && token.value === 'goto' &&
2768 lookahead.type === Identifier && lookahead.value !== 'goto') {
2769 next(); return parseGotoStatement(flowContext);
2770 }
2771 if (trackLocations) locations.pop();
2772
2773 return parseAssignmentOrCallStatement(flowContext);
2774 }
2775
2776 function parseLabelStatement(flowContext) {
2777 var nameToken = token
2778 , label = parseIdentifier();
2779
2780 if (options.scope) {
2781 scopeIdentifierName('::' + nameToken.value + '::');
2782 attachScope(label, true);
2783 }
2784
2785 expect('::');
2786
2787 flowContext.addLabel(nameToken.value, nameToken);
2788 return finishNode(ast.labelStatement(label));
2789 }
2790
2791 function parseBreakStatement() {
2792 return finishNode(ast.breakStatement());
2793 }
2794
2795 function parseGotoStatement(flowContext) {
2796 var name = token.value
2797 , gotoToken = previousToken
2798 , label = parseIdentifier();
2799
2800 flowContext.addGoto(name, gotoToken);
2801 return finishNode(ast.gotoStatement(label));
2802 }
2803
2804 function parseDoStatement(flowContext) {
2805 if (options.scope) createScope();
2806 flowContext.pushScope();
2807 var body = parseBlock(flowContext);
2808 flowContext.popScope();
2809 if (options.scope) destroyScope();
2810 expect('end');
2811 return finishNode(ast.doStatement(body));
2812 }
2813
2814 function parseWhileStatement(flowContext) {
2815 var condition = parseExpectedExpression(flowContext);
2816 expect('do');
2817 if (options.scope) createScope();
2818 flowContext.pushScope(true);
2819 var body = parseBlock(flowContext);
2820 flowContext.popScope();
2821 if (options.scope) destroyScope();
2822 expect('end');
2823 return finishNode(ast.whileStatement(condition, body));
2824 }
2825
2826 function parseRepeatStatement(flowContext) {
2827 if (options.scope) createScope();
2828 flowContext.pushScope(true);
2829 var body = parseBlock(flowContext);
2830 expect('until');
2831 flowContext.raiseDeferredErrors();
2832 var condition = parseExpectedExpression(flowContext);
2833 flowContext.popScope();
2834 if (options.scope) destroyScope();
2835 return finishNode(ast.repeatStatement(condition, body));
2836 }
2837
2838 function parseReturnStatement(flowContext) {
2839 var expressions = [];
2840
2841 if ('end' !== token.value) {
2842 var expression = parseExpression(flowContext);
2843 if (null != expression) expressions.push(expression);
2844 while (consume(',')) {
2845 expression = parseExpectedExpression(flowContext);
2846 expressions.push(expression);
2847 }
2848 consume(';'); // grammar tells us ; is optional here.
2849 }
2850 return finishNode(ast.returnStatement(expressions));
2851 }
2852
2853 function parseIfStatement(flowContext) {
2854 var clauses = []
2855 , condition
2856 , body
2857 , marker;
2858 if (trackLocations) {
2859 marker = locations[locations.length - 1];
2860 locations.push(marker);
2861 }
2862 condition = parseExpectedExpression(flowContext);
2863 expect('then');
2864 if (options.scope) createScope();
2865 flowContext.pushScope();
2866 body = parseBlock(flowContext);
2867 flowContext.popScope();
2868 if (options.scope) destroyScope();
2869 clauses.push(finishNode(ast.ifClause(condition, body)));
2870
2871 if (trackLocations) marker = createLocationMarker();
2872 while (consume('elseif')) {
2873 pushLocation(marker);
2874 condition = parseExpectedExpression(flowContext);
2875 expect('then');
2876 if (options.scope) createScope();
2877 flowContext.pushScope();
2878 body = parseBlock(flowContext);
2879 flowContext.popScope();
2880 if (options.scope) destroyScope();
2881 clauses.push(finishNode(ast.elseifClause(condition, body)));
2882 if (trackLocations) marker = createLocationMarker();
2883 }
2884
2885 if (consume('else')) {
2886 if (trackLocations) {
2887 marker = new Marker(previousToken);
2888 locations.push(marker);
2889 }
2890 if (options.scope) createScope();
2891 flowContext.pushScope();
2892 body = parseBlock(flowContext);
2893 flowContext.popScope();
2894 if (options.scope) destroyScope();
2895 clauses.push(finishNode(ast.elseClause(body)));
2896 }
2897
2898 expect('end');
2899 return finishNode(ast.ifStatement(clauses));
2900 }
2901
2902 function parseForStatement(flowContext) {
2903 var variable = parseIdentifier()
2904 , body;
2905
2906 if (options.scope) {
2907 createScope();
2908 scopeIdentifier(variable);
2909 }
2910 if (consume('=')) {
2911 var start = parseExpectedExpression(flowContext);
2912 expect(',');
2913 var end = parseExpectedExpression(flowContext);
2914 var step = consume(',') ? parseExpectedExpression(flowContext) : null;
2915
2916 expect('do');
2917 flowContext.pushScope(true);
2918 body = parseBlock(flowContext);
2919 flowContext.popScope();
2920 expect('end');
2921 if (options.scope) destroyScope();
2922
2923 return finishNode(ast.forNumericStatement(variable, start, end, step, body));
2924 }
2925 else {
2926 var variables = [variable];
2927 while (consume(',')) {
2928 variable = parseIdentifier();
2929 if (options.scope) scopeIdentifier(variable);
2930 variables.push(variable);
2931 }
2932 expect('in');
2933 var iterators = [];
2934 do {
2935 var expression = parseExpectedExpression(flowContext);
2936 iterators.push(expression);
2937 } while (consume(','));
2938
2939 expect('do');
2940 flowContext.pushScope(true);
2941 body = parseBlock(flowContext);
2942 flowContext.popScope();
2943 expect('end');
2944 if (options.scope) destroyScope();
2945
2946 return finishNode(ast.forGenericStatement(variables, iterators, body));
2947 }
2948 }
2949
2950 function parseLocalStatement(flowContext) {
2951 var name
2952 , declToken = previousToken;
2953
2954 if (Identifier === token.type) {
2955 var variables = []
2956 , init = [];
2957
2958 do {
2959 name = parseIdentifier();
2960
2961 variables.push(name);
2962 flowContext.addLocal(name.name, declToken);
2963 } while (consume(','));
2964
2965 if (consume('=')) {
2966 do {
2967 var expression = parseExpectedExpression(flowContext);
2968 init.push(expression);
2969 } while (consume(','));
2970 }
2971 if (options.scope) {
2972 for (var i = 0, l = variables.length; i < l; ++i) {
2973 scopeIdentifier(variables[i]);
2974 }
2975 }
2976
2977 return finishNode(ast.localStatement(variables, init));
2978 }
2979 if (consume('function')) {
2980 name = parseIdentifier();
2981 flowContext.addLocal(name.name, declToken);
2982
2983 if (options.scope) {
2984 scopeIdentifier(name);
2985 createScope();
2986 }
2987 return parseFunctionDeclaration(name, true);
2988 } else {
2989 raiseUnexpectedToken('<name>', token);
2990 }
2991 }
2992
2993 function parseAssignmentOrCallStatement(flowContext) {
2994 var previous = token
2995 , marker, startMarker;
2996 var lvalue, base, name;
2997
2998 var targets = [];
2999
3000 if (trackLocations) startMarker = createLocationMarker();
3001
3002 do {
3003 if (trackLocations) marker = createLocationMarker();
3004
3005 if (Identifier === token.type) {
3006 name = token.value;
3007 base = parseIdentifier();
3008 if (options.scope) attachScope(base, scopeHasName(name));
3009 lvalue = true;
3010 } else if ('(' === token.value) {
3011 next();
3012 base = parseExpectedExpression(flowContext);
3013 expect(')');
3014 lvalue = false;
3015 } else {
3016 return unexpected(token);
3017 }
3018
3019 both: for (;;) {
3020 var newBase;
3021
3022 switch (StringLiteral === token.type ? '"' : token.value) {
3023 case '.':
3024 case '[':
3025 lvalue = true;
3026 break;
3027 case ':':
3028 case '(':
3029 case '{':
3030 case '"':
3031 lvalue = null;
3032 break;
3033 default:
3034 break both;
3035 }
3036
3037 base = parsePrefixExpressionPart(base, marker, flowContext);
3038 }
3039
3040 targets.push(base);
3041
3042 if (',' !== token.value)
3043 break;
3044
3045 if (!lvalue) {
3046 return unexpected(token);
3047 }
3048
3049 next();
3050 } while (true);
3051
3052 if (targets.length === 1 && lvalue === null) {
3053 pushLocation(marker);
3054 return finishNode(ast.callStatement(targets[0]));
3055 } else if (!lvalue) {
3056 return unexpected(token);
3057 }
3058
3059 expect('=');
3060
3061 var values = [];
3062
3063 do {
3064 values.push(parseExpectedExpression(flowContext));
3065 } while (consume(','));
3066
3067 pushLocation(startMarker);
3068 return finishNode(ast.assignmentStatement(targets, values));
3069 }
3070
3071 function parseIdentifier() {
3072 markLocation();
3073 var identifier = token.value;
3074 if (Identifier !== token.type) raiseUnexpectedToken('<name>', token);
3075 next();
3076 return finishNode(ast.identifier(identifier));
3077 }
3078
3079 function parseFunctionDeclaration(name, isLocal) {
3080 var flowContext = makeFlowContext();
3081 flowContext.pushScope();
3082
3083 var parameters = [];
3084 expect('(');
3085 if (!consume(')')) {
3086 while (true) {
3087 if (Identifier === token.type) {
3088 var parameter = parseIdentifier();
3089 if (options.scope) scopeIdentifier(parameter);
3090
3091 parameters.push(parameter);
3092
3093 if (consume(',')) continue;
3094 }
3095 else if (VarargLiteral === token.type) {
3096 flowContext.allowVararg = true;
3097 parameters.push(parsePrimaryExpression(flowContext));
3098 } else {
3099 raiseUnexpectedToken('<name> or \'...\'', token);
3100 }
3101 expect(')');
3102 break;
3103 }
3104 }
3105
3106 var body = parseBlock(flowContext);
3107 flowContext.popScope();
3108 expect('end');
3109 if (options.scope) destroyScope();
3110
3111 isLocal = isLocal || false;
3112 return finishNode(ast.functionStatement(name, parameters, isLocal, body));
3113 }
3114
3115 function parseFunctionName() {
3116 var base, name, marker;
3117
3118 if (trackLocations) marker = createLocationMarker();
3119 base = parseIdentifier();
3120
3121 if (options.scope) {
3122 attachScope(base, scopeHasName(base.name));
3123 createScope();
3124 }
3125
3126 while (consume('.')) {
3127 pushLocation(marker);
3128 name = parseIdentifier();
3129 base = finishNode(ast.memberExpression(base, '.', name));
3130 }
3131
3132 if (consume(':')) {
3133 pushLocation(marker);
3134 name = parseIdentifier();
3135 base = finishNode(ast.memberExpression(base, ':', name));
3136 if (options.scope) scopeIdentifierName('self');
3137 }
3138
3139 return base;
3140 }
3141
3142 function parseTableConstructor(flowContext) {
3143 var fields = []
3144 , key, value;
3145
3146 while (true) {
3147 markLocation();
3148 if (Punctuator === token.type && consume('[')) {
3149 key = parseExpectedExpression(flowContext);
3150 expect(']');
3151 expect('=');
3152 value = parseExpectedExpression(flowContext);
3153 fields.push(finishNode(ast.tableKey(key, value)));
3154 } else if (Identifier === token.type) {
3155 if ('=' === lookahead.value) {
3156 key = parseIdentifier();
3157 next();
3158 value = parseExpectedExpression(flowContext);
3159 fields.push(finishNode(ast.tableKeyString(key, value)));
3160 } else {
3161 value = parseExpectedExpression(flowContext);
3162 fields.push(finishNode(ast.tableValue(value)));
3163 }
3164 } else {
3165 if (null == (value = parseExpression(flowContext))) {
3166 locations.pop();
3167 break;
3168 }
3169 fields.push(finishNode(ast.tableValue(value)));
3170 }
3171 if (',;'.indexOf(token.value) >= 0) {
3172 next();
3173 continue;
3174 }
3175 break;
3176 }
3177 expect('}');
3178 return finishNode(ast.tableConstructorExpression(fields));
3179 }
3180
3181 function parseExpression(flowContext) {
3182 var expression = parseSubExpression(0, flowContext);
3183 return expression;
3184 }
3185
3186 function parseExpectedExpression(flowContext) {
3187 var expression = parseExpression(flowContext);
3188 if (null == expression) raiseUnexpectedToken('<expression>', token);
3189 else return expression;
3190 }
3191
3192 function binaryPrecedence(operator) {
3193 var charCode = operator.charCodeAt(0)
3194 , length = operator.length;
3195
3196 if (1 === length) {
3197 switch (charCode) {
3198 case 94: return 12; // ^
3199 case 42: case 47: case 37: return 10; // * / %
3200 case 43: case 45: return 9; // + -
3201 case 38: return 6; // &
3202 case 126: return 5; // ~
3203 case 124: return 4; // |
3204 case 60: case 62: return 3; // < >
3205 }
3206 } else if (2 === length) {
3207 switch (charCode) {
3208 case 47: return 10; // //
3209 case 46: return 8; // ..
3210 case 60: case 62:
3211 if('<<' === operator || '>>' === operator) return 7; // << >>
3212 return 3; // <= >=
3213 case 61: case 126: return 3; // == ~=
3214 case 111: return 1; // or
3215 }
3216 } else if (97 === charCode && 'and' === operator) return 2;
3217 return 0;
3218 }
3219
3220 function parseSubExpression(minPrecedence, flowContext) {
3221 var operator = token.value
3222 , expression, marker;
3223
3224 if (trackLocations) marker = createLocationMarker();
3225 if (isUnary(token)) {
3226 markLocation();
3227 next();
3228 var argument = parseSubExpression(10, flowContext);
3229 if (argument == null) raiseUnexpectedToken('<expression>', token);
3230 expression = finishNode(ast.unaryExpression(operator, argument));
3231 }
3232 if (null == expression) {
3233 expression = parsePrimaryExpression(flowContext);
3234 if (null == expression) {
3235 expression = parsePrefixExpression(flowContext);
3236 }
3237 }
3238 if (null == expression) return null;
3239
3240 var precedence;
3241 while (true) {
3242 operator = token.value;
3243
3244 precedence = (Punctuator === token.type || Keyword === token.type) ?
3245 binaryPrecedence(operator) : 0;
3246
3247 if (precedence === 0 || precedence <= minPrecedence) break;
3248 if ('^' === operator || '..' === operator) --precedence;
3249 next();
3250 var right = parseSubExpression(precedence, flowContext);
3251 if (null == right) raiseUnexpectedToken('<expression>', token);
3252 if (trackLocations) locations.push(marker);
3253 expression = finishNode(ast.binaryExpression(operator, expression, right));
3254
3255 }
3256 return expression;
3257 }
3258
3259 function parsePrefixExpressionPart(base, marker, flowContext) {
3260 var expression, identifier;
3261
3262 if (Punctuator === token.type) {
3263 switch (token.value) {
3264 case '[':
3265 pushLocation(marker);
3266 next();
3267 expression = parseExpectedExpression(flowContext);
3268 expect(']');
3269 return finishNode(ast.indexExpression(base, expression));
3270 case '.':
3271 pushLocation(marker);
3272 next();
3273 identifier = parseIdentifier();
3274 return finishNode(ast.memberExpression(base, '.', identifier));
3275 case ':':
3276 pushLocation(marker);
3277 next();
3278 identifier = parseIdentifier();
3279 base = finishNode(ast.memberExpression(base, ':', identifier));
3280 pushLocation(marker);
3281 return parseCallExpression(base, flowContext);
3282 case '(': case '{': // args
3283 pushLocation(marker);
3284 return parseCallExpression(base, flowContext);
3285 }
3286 } else if (StringLiteral === token.type) {
3287 pushLocation(marker);
3288 return parseCallExpression(base, flowContext);
3289 }
3290
3291 return null;
3292 }
3293
3294 function parsePrefixExpression(flowContext) {
3295 var base, name, marker;
3296
3297 if (trackLocations) marker = createLocationMarker();
3298 if (Identifier === token.type) {
3299 name = token.value;
3300 base = parseIdentifier();
3301 if (options.scope) attachScope(base, scopeHasName(name));
3302 } else if (consume('(')) {
3303 base = parseExpectedExpression(flowContext);
3304 expect(')');
3305 } else {
3306 return null;
3307 }
3308 for (;;) {
3309 var newBase = parsePrefixExpressionPart(base, marker, flowContext);
3310 if (newBase === null)
3311 break;
3312 base = newBase;
3313 }
3314
3315 return base;
3316 }
3317
3318 function parseCallExpression(base, flowContext) {
3319 if (Punctuator === token.type) {
3320 switch (token.value) {
3321 case '(':
3322 if (!features.emptyStatement) {
3323 if (token.line !== previousToken.line)
3324 raise(null, errors.ambiguousSyntax, token.value);
3325 }
3326 next();
3327 var expressions = [];
3328 var expression = parseExpression(flowContext);
3329 if (null != expression) expressions.push(expression);
3330 while (consume(',')) {
3331 expression = parseExpectedExpression(flowContext);
3332 expressions.push(expression);
3333 }
3334
3335 expect(')');
3336 return finishNode(ast.callExpression(base, expressions));
3337
3338 case '{':
3339 markLocation();
3340 next();
3341 var table = parseTableConstructor(flowContext);
3342 return finishNode(ast.tableCallExpression(base, table));
3343 }
3344 } else if (StringLiteral === token.type) {
3345 return finishNode(ast.stringCallExpression(base, parsePrimaryExpression(flowContext)));
3346 }
3347
3348 raiseUnexpectedToken('function arguments', token);
3349 }
3350
3351 function parsePrimaryExpression(flowContext) {
3352 var literals = StringLiteral | NumericLiteral | BooleanLiteral | NilLiteral | VarargLiteral
3353 , value = token.value
3354 , type = token.type
3355 , marker;
3356
3357 if (trackLocations) marker = createLocationMarker();
3358
3359 if (type === VarargLiteral && !flowContext.allowVararg) {
3360 raise(token, errors.cannotUseVararg, token.value);
3361 }
3362
3363 if (type & literals) {
3364 pushLocation(marker);
3365 var raw = input.slice(token.range[0], token.range[1]);
3366 next();
3367 return finishNode(ast.literal(type, value, raw));
3368 } else if (Keyword === type && 'function' === value) {
3369 pushLocation(marker);
3370 next();
3371 if (options.scope) createScope();
3372 return parseFunctionDeclaration(null);
3373 } else if (consume('{')) {
3374 pushLocation(marker);
3375 return parseTableConstructor(flowContext);
3376 }
3377 }
3378
3379 exports.parse = parse;
3380
3381 var versionFeatures = {
3382 '5.1': {
3383 },
3384 '5.2': {
3385 labels: true,
3386 emptyStatement: true,
3387 hexEscapes: true,
3388 skipWhitespaceEscape: true,
3389 strictEscapes: true,
3390 relaxedBreak: true
3391 },
3392 '5.3': {
3393 labels: true,
3394 emptyStatement: true,
3395 hexEscapes: true,
3396 skipWhitespaceEscape: true,
3397 strictEscapes: true,
3398 unicodeEscapes: true,
3399 bitwiseOperators: true,
3400 integerDivision: true,
3401 relaxedBreak: true
3402 },
3403 'LuaJIT': {
3404 labels: true,
3405 contextualGoto: true,
3406 hexEscapes: true,
3407 skipWhitespaceEscape: true,
3408 strictEscapes: true,
3409 unicodeEscapes: true,
3410 imaginaryNumbers: true,
3411 integerSuffixes: true
3412 }
3413 };
3414
3415 function parse(_input, _options) {
3416 if ('undefined' === typeof _options && 'object' === typeof _input) {
3417 _options = _input;
3418 _input = undefined;
3419 }
3420 if (!_options) _options = {};
3421
3422 input = _input || '';
3423 options = assign({}, defaultOptions, _options);
3424 index = 0;
3425 line = 1;
3426 lineStart = 0;
3427 length = input.length;
3428 scopes = [[]];
3429 scopeDepth = 0;
3430 globals = [];
3431 locations = [];
3432
3433 if (!Object.prototype.hasOwnProperty.call(versionFeatures, options.luaVersion)) {
3434 throw new Error(sprintf("Lua version '%1' not supported", options.luaVersion));
3435 }
3436
3437 features = assign({}, versionFeatures[options.luaVersion]);
3438 if (options.extendedIdentifiers !== void 0)
3439 features.extendedIdentifiers = !!options.extendedIdentifiers;
3440
3441 if (!Object.prototype.hasOwnProperty.call(encodingModes, options.encodingMode)) {
3442 throw new Error(sprintf("Encoding mode '%1' not supported", options.encodingMode));
3443 }
3444
3445 encodingMode = encodingModes[options.encodingMode];
3446
3447 if (options.comments) comments = [];
3448 if (!options.wait) return end();
3449 return exports;
3450 }
3451 exports.write = write;
3452
3453 function write(_input) {
3454 input += String(_input);
3455 length = input.length;
3456 return exports;
3457 }
3458 exports.end = end;
3459
3460 function end(_input) {
3461 if ('undefined' !== typeof _input) write(_input);
3462 if (input && input.substr(0, 2) === '#!') input = input.replace(/^.*/, function (line) {
3463 return line.replace(/./g, ' ');
3464 });
3465
3466 length = input.length;
3467 trackLocations = options.locations || options.ranges;
3468 lookahead = lex();
3469
3470 var chunk = parseChunk();
3471 if (options.comments) chunk.comments = comments;
3472 if (options.scope) chunk.globals = globals;
3473 if (locations.length > 0)
3474 throw new Error('Location tracking failed. This is most likely a bug in luaparse');
3475
3476 return chunk;
3477 }
3478
3479 }));
3480
3481 });
3482
3483 ace.define("ace/mode/lua_worker",[], function(require, exports, module) {
3484 "use strict";
3485
3486 var oop = require("../lib/oop");
3487 var Mirror = require("../worker/mirror").Mirror;
3488 var luaparse = require("../mode/lua/luaparse");
3489
3490 var Worker = exports.Worker = function(sender) {
3491 Mirror.call(this, sender);
3492 this.setTimeout(500);
3493 };
3494
3495 oop.inherits(Worker, Mirror);
3496
3497 (function() {
3498
3499 this.onUpdate = function() {
3500 var value = this.doc.getValue();
3501 var errors = [];
3502 try {
3503 luaparse.parse(value);
3504 } catch(e) {
3505 if (e instanceof luaparse.SyntaxError) {
3506 errors.push({
3507 row: e.line - 1,
3508 column: e.column,
3509 text: e.message,
3510 type: "error"
3511 });
3512 }
3513 }
3514 this.sender.emit("annotate", errors);
3515 };
3516
3517 }).call(Worker.prototype);
3518
3519 });